篇幅一,介紹了為什么可以通過(guò)mas_key 定位問(wèn)題。如下:
http://www.itdecent.cn/p/710f742ca71a
如果一個(gè)布局很多的頁(yè)面,突然出現(xiàn)這種問(wèn)題呢?比如下面的,
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:0x1c08a0a80 UILabel:0x112a1c600.left == UIView:0x112a1b830.left + 5>",
"<MASLayoutConstraint:0x1c08a1080 UILabel:0x112a1d1e0.left == UIView:0x112a1b830.left + 5>",
"<MASLayoutConstraint:0x1c08a1140 UILabel:0x112a1d1e0.right == UILabel:0x112a1c600.left - 5>"
)
信息只有UILabel UIView,我們可以通過(guò)runtime,獲取到ivar 信息,然后手動(dòng)給ivar 設(shè)置mas_key 值。
代碼如下:
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([self class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
id pointer = object_getIvar(self, ivar);
if ([pointer isKindOfClass:[UIView class]]) {
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
UIView *v = (UIView *)pointer;
v.mas_key = name;
}
}
free(ivars);
}
通過(guò)判斷ivar 是不是UIView 的子類,然后設(shè)置mas_key 的值為ivar的name.這樣子提示信息就很詳細(xì)了。
可以提取一個(gè)全局的函數(shù)出來(lái)
/*
* 設(shè)置ivar 的 mas_key 值為 對(duì)應(yīng)的名字比如
@interface PBTTestClass : NSObject
@property (nonatomic, strong) UIButton *payButton;
@end
PBTTestClass *c = [PBTTestClass new];
autoSetClassMas_key(c);
就設(shè)置 c.payButton.mas_key = @"_payButton";
*
*/
static void autoSetClassMas_key(NSObject *instance) {
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList(instance.class, &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
id pointer = object_getIvar(instance, ivar);
if ([pointer isKindOfClass:[UIView class]]) {
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
UIView *v = (UIView *)pointer;
v.mas_key = name;
}
}
free(ivars);
}
}