在xib拖了控件后直接在awakeFromNib、layoutSubviews中獲取子控件的frame時(shí)只會(huì)返回xib中設(shè)置好的frame(在- (void)drawRect:(CGRect)rect中能獲取正確的frame但會(huì)引起cpu介入計(jì)算不推薦,因?yàn)闆]有g(shù)pu繪圖效率高,會(huì)引起較大的內(nèi)存占用),解決方法:
- (void)layoutSubviews
{
? ? [super layoutSubviews];
? ? [self.contentView setNeedsLayout];
? ? [self.contentView layoutIfNeeded];
//調(diào)用上述方法后可獲取正確frame
}
關(guān)于layoutSubviews、layoutIfNeeded、setNeedsLayout的定義很多隨便貼一個(gè)鏈接http://www.itdecent.cn/p/eb2c4bb4e3f1
此處需要區(qū)別cell.contentView和cell的區(qū)別(即[self.contentView setNeedsLayout]和[self setNeedsLayout]的區(qū)別)

每個(gè)視圖對(duì)象都可以調(diào)用setNeedsLayout、layoutIfNeeded方法,?[self.contentView setNeedsLayout]、 [self.contentView layoutIfNeeded]是在self.contentView上添加了刷新標(biāo)記,執(zhí)行的也是self.contentView的layoutSubviews。將self.contentView換成self就會(huì)執(zhí)行cell上的layoutSubviews,會(huì)死循環(huán)奔潰。
綜上所述若想獲得AutoLayout自適應(yīng)后的frame,需要先調(diào)用獲取對(duì)象的父視圖的[self.contentView setNeedsLayout]、 [self.contentView layoutIfNeeded]進(jìn)行刷新(注意循環(huán)調(diào)用問題),若在VC中則是調(diào)用[self.view setNeedsLayout]、 [self.view layoutIfNeeded]