Masonry 布局約束沖突

Masonry 布局約束沖突

在涉及一些自動布局的時候,使用Masonry 布局會起到事半功倍的效果,本人覺得比蘋果的原生的自動布局約束好使用,但是會遇到各種各樣的約束沖突。少量的約束沖突對性能影響不大,但是作為一名程序猿,不得有半點的馬虎,很小的一個問題都會影響app的性能。當約束沖突很多的時候,就會造成內(nèi)存的增加,到達某一個臨界值的時候,有可能會是APP崩潰。所以精益求精,盡量減少,或者沒有約束沖突是最好的追求。

本人就在大量使用cell的時候遇到大量的約束沖突。

發(fā)送環(huán)境

封裝一個控件,想讓其內(nèi)部自己改變自己的狀態(tài)。使用Masonry 很方便,但是當時內(nèi)部確實是自動適應。所有的布局沒有問題,確有一堆約束沖突。

查找原因

是因為外部兩次約束 該空間的寬度。

比如:

圖1

圖1,該方法是暴露給外面刷新數(shù)據(jù)的,并且自動修改寬度。

圖2

圖2,而在外面其他地方,又一次去動態(tài)修改該空間的寬度

所以會有約束沖突

2017-03-01 18:14:53.467635 YXLiveVideoApp[599:142306] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<MASLayoutConstraint:0x174ca8760 UIImageView:0x15fa9ffe0.left == YXLiveTrueLoveRegimentalView:0x15fa9fe30.left>",
    "<MASLayoutConstraint:0x174ca8a00 YXLiveTrueLoveRegimentalView:0x15fa9fe30.right == UIImageView:0x15fa9ffe0.right>",
    "<MASLayoutConstraint:0x170eb9ce0 UIImageView:0x15fa9ffe0.width == 0>",
    "<MASLayoutConstraint:0x174ca9840 YXLiveTrueLoveRegimentalView:0x15fa9fe30.width == 300>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x170eb9ce0 UIImageView:0x15fa9ffe0.width == 0>

解決辦法

1、刪除 圖2 代碼,解決約束沖突。

2、設(shè)置約束優(yōu)先級。

/**
 *  Sets the NSLayoutConstraint priority to a float or MASLayoutPriority
 */
- (MASConstraint * (^)(MASLayoutPriority priority))priority;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityLow
 */
- (MASConstraint * (^)())priorityLow;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium
 */
- (MASConstraint * (^)())priorityMedium;

/**
 *  Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh
 */
- (MASConstraint * (^)())priorityHigh;

比如:

[self.trueLoveRegimentalView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(300).priorityHigh;
        }];

優(yōu)先級默認是 中等

總結(jié):

在需要根據(jù)數(shù)據(jù)動態(tài)改變空間的大小的時候,本人認為優(yōu)選方案,控件內(nèi)部根據(jù)數(shù)據(jù)刷新去動態(tài)改變控件大小。外部只需要關(guān)心控件的 位置需要放在那里。

這樣就不需要外面使用的時候關(guān)心大小。類似于 UILabel 自動伸縮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容