以编程方式将UIScrollView添加到UIView不能在viewDidLoad中工作,但在viewDidAppear中工作?

问题描述:

我正在使用自动布局。以编程方式将UIScrollView添加到UIView不能在viewDidLoad中工作,但在viewDidAppear中工作?

我像下面的代码一样以编程方式向uview查看scrollview。我试图运行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)]; 
+0

你在哪里使用autolayout?对于以编程方式创建的视图,您必须以编程方式添加自动布局。 –

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

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

+0

是的你是对的,我重新编写滚动视图框= CGRectMake(0,0,self.view.frame.size.width,self。 view.frame.size.height - slideTitleHeight)];它的工作原理 –

这是viewDidAppear方法你得到一个视图的实际布局(帧)b'coz。

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

[self setNeedsLayout];

[self layoutIfNeeded];

注意:当您使用自动布局则建议不要设置的图幅。您只需要给予约束即可将其置于正确的位置。

+0

您的意思是:[self.view setNeedsLayout]; [self.view layoutIfNeeded];?我只是尝试调用这些方法在initShopView之前加载视图,仍然无法正常工作 –

而不是创建框架,使用AutoLayout设置您的意见。它也可以在viewDidLoad中工作。 帧使视图渲染更加复杂,并且无法在所有设备大小上正常工作。