今天在自定义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];
}
- 何时使用layout
本文深入探讨了在自定义Button时遇到的layoutSubviews方法调用问题,特别是使用sizeToFit自适应方法且未在初始化时设置frame的情况。通过分析不同方法的触发时机,揭示了布局更新的机制。
526

被折叠的 条评论
为什么被折叠?



