AutoLayout布局時(shí)無法正確獲取子控件的frame

在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]

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容