以编程方式将 UIScrollView 添加到 UIView 在 vi​​ewDidLoad 中不起作用但在 viewDidAppear 中起作用?

Add UIScrollView to UIView programmatically not work in viewDidLoad but work in viewDidAppear?

我正在使用自动布局。

我像下面的代码一样以编程方式向 uiview 添加了一个滚动视图。我正在尝试 运行 视图中的 initShopView 确实已加载,但它只是不起作用并且根本没有添加要查看的滚动视图。我已经看到视图层次结构捕获。

class variables:

@property(strong,nonatomic) UIScrollView *shopScrollView;
@property(strong,nonatomic) UIView *headView;
@property(strong,nonatomic) UIButton *favoriteButton;


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initShopView];// not work

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self initShopView];// will work
}

-(void)initShopView{
    self.shopScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.superview.frame.size.height - slideTitleHeight)];
    self.shopScrollView.contentSize = CGSizeMake(self.view.frame.size.width, 800);
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];

    self.favoriteButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 60, 10, 55, 55)];
    [self.favoriteButton setTitle:@"Favorite" forState:UIControlStateNormal];
    [self.favoriteButton setImage:[UIImage imageNamed:@"favoriteGreen.png"] forState:UIControlStateNormal];



    [self.headView addSubview:self.favoriteButton];
    [self.shopScrollView addSubview:self.headView];
    [self.view addSubview:self.shopScrollView];
}

@Phillip Mills 给出了解决方案。我的滚动视图的框架是

self.shopScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.superview.frame.size.height - slideTitleHeight)];

解决方案是:

self.shopScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - slideTitleHeight)];

这是因为在 viewDidAppear 方法中,您正在获取视图的实际布局(框架)。

要在 viewDidLoad 中工作,您需要在 [self initShopView]; 方法之上调用这些方法。

[self setNeedsLayout];

[self layoutIfNeeded];

注意:当您使用自动布局时,不建议设置视图框架。您只需要为视图提供约束以将其放置在正确的位置。

viewDidLoad 中,您的视图没有 superview,因为它尚未插入到视图层次结构中。这意味着您将滚动视图的高度设置为零。

如果您使用 Xcode 的视图调试,您将在列表中看到滚动视图,但带有 "wrong" 框架。

不用创建框架,而是使用 AutoLayout 来设置您的视图。它也将在 viewDidLoad 中工作。 框架使视图渲染更加复杂,并且无法在所有设备尺寸上正常工作。