首页 > 解决方案 > 通过 addSubView 调用时,自定义视图 xib 上的 UIScrollView 不滚动

问题描述

如图所示,我在 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 呢?

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

github:项目示例

标签: iosobjective-cuiscrollviewautolayout

解决方案


这是因为你没有为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];
}

推荐阅读