iOS初学之OC

关于layoutSubviews方法何时使用的总结

2017-05-26  本文已影响79人  CharlesAn

今天在自定义button时,遇到了关于layoutSubviews方法调用的问题,由于使用的是sizeTofit自适应的方法,所以初始化时并没有给按钮设置frame,,只是在layout方法里改变了titleLable和imageView的位置,按钮却能正常显示,就想到什么时候走了layout方法。

- (void)layoutSubviews{
    
   [super layoutSubviews];
    NSLog(@"layout1");
    self.backgroundColor = [UIColor redColor];
   self.titleLabel.frame =    CGRectMake(self.imageView.frame.origin.x, self.titleLabel.frame.origin.y, self.titleLabel.frame.size.width, self.titleLabel.frame.size.height);
   
    self.imageView.frame = CGRectMake(CGRectGetMaxX(self.titleLabel.frame), self.imageView.frame.origin.y, self.imageView.frame.size.width, self.imageView.frame.size.height);
}
- (void)setTitle:(NSString *)title forState:(UIControlState)state{
    
    [super setTitle:title forState:state];
    NSLog(@"settitle");
    [self sizeToFit];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state{
    NSLog(@"setimage");
    [super setImage:image forState:state];
    [self sizeToFit];
}

1.init方法不会触发
2.改变frame大小时会触发layoutSubviews方法
3.addSubview会触发layoutSubviews
上一篇下一篇

猜你喜欢

热点阅读