在xib拖了控件后直接在awakeFromNib、layoutSubviews中获取子控件的frame时只会返回xib中设置好的frame(在- (void)drawRect:(CGRect)rect中能获取正确的frame但会引起cpu介入计算不推荐,因为没有gpu绘图效率高,会引起较大的内存占用),解决方法:
- (void)layoutSubviews
{
[super layoutSubviews];
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
//调用上述方法后可获取正确frame
}
关于layoutSubviews、layoutIfNeeded、setNeedsLayout的定义很多随便贴一个链接//www.greatytc.com/p/eb2c4bb4e3f1
此处需要区别cell.contentView和cell的区别(即[self.contentView setNeedsLayout]和[self setNeedsLayout]的区别)
每个视图对象都可以调用setNeedsLayout、layoutIfNeeded方法, [self.contentView setNeedsLayout]、 [self.contentView layoutIfNeeded]是在self.contentView上添加了刷新标记,执行的也是self.contentView的layoutSubviews。将self.contentView换成self就会执行cell上的layoutSubviews,会死循环奔溃。
综上所述若想获得AutoLayout自适应后的frame,需要先调用获取对象的父视图的[self.contentView setNeedsLayout]、 [self.contentView layoutIfNeeded]进行刷新(注意循环调用问题),若在VC中则是调用[self.view setNeedsLayout]、 [self.view layoutIfNeeded]