【问题标题】:UIScrollView on custom view xib not scrolling when called via addSubView通过 addSubView 调用时,自定义视图 xib 上的 UIScrollView 不滚动
【发布时间】:2019-03-12 15:11:52
【问题描述】:

如图所示,我在 XIB 中有一个高度为 800 的自定义视图:

这是层次结构:

这是我的 customView.m 上的代码:

- (id)initWithFrame:(CGRect)frame
{
NSLog(@"initWithFrame");
self = [super initWithFrame:frame];
if (self) {
    [self setup];
}
return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"initWithCoder");
self = [super initWithCoder:aDecoder];
if(self) {
    [self setup];
}
return self;
}

- (void)setup {

[[NSBundle mainBundle] loadNibNamed:@"customView" owner:self options:nil];
[self addSubview:self.view];
self.view.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, CGRectGetHeight(self.view.frame));
//[self.myscrollview setContentSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width, 2000)];
NSLog(@"contentSize Height :%f", self.myscrollview.contentSize.height);
NSLog(@"contentView Height :%f", self.contentView.frame.size.height);
}

并在我的 viewController 视图上添加自定义视图:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

customView *myView = [[customView alloc] init];

[self.view addSubview:myView];

}

它已加载,但 scrollView 没有滚动。然后我检查 customView 和 contentView 高度,它返回 800,但 scrollView contentSize 高度返回 0。所以我尝试将 contentSize 设置为 2000,但它仍然不滚动。让我感到困惑的是,为什么在我将 scrollView 尾随、前导、底部和顶部 0 设置为 superView 后,它没有跟随 contentView 的高度,而是返回 0。那我应该如何设置 contentSize?

nb: contentView 的高度和宽度等于 superView 并且优先级设置为 250

github:project example

【问题讨论】:

  • 当您将其添加为子视图时,为视图添加适当的约束。这将解决您的问题。 stackoverflow.com/questions/35294571/…
  • 我没有限制代码。
  • 但你应该这样做。你在设计时所拥有的一切都是有约束的。如果你不应用约束来查看添加的运行时,它永远不会给你想要的结果。

标签: ios objective-c uiscrollview autolayout


【解决方案1】:

这是因为您没有为myView 设置框架。用下面的代码替换您的 viewDidLoad 方法,它将按预期工作

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
     customView *customV = [[customView alloc] initWithFrame:self.wantToShowHereView.bounds];
    [self.wantToShowHereView addSubview:customV];
}

【讨论】:

  • 谢谢!它的工作不是我所期望的,因为滚动直到下面的最后一个对象才滚动,而且它的超级滞后,你知道为什么吗?
  • 下面最后一个对象是什么?您的示例中的滚动视图仅包含 1 个 UILabel,而且很流畅
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多