button奇葩问题解决

项目中要封装NextButton,开始要处理enable 的不同状态,无法重写enabled的setter方法(可能苹果内部改了其实例变量名字),后来用重写

setNeedsLayout方法,解决了

-(void)setNeedsLayout

{

if(self.enabled) {

NSLog(@"enabled");

UIColor*color = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"button"]];

UIColor*cl = [colorcolorWithAlphaComponent:1.0f];

[selfsetBackgroundColor:cl];

if(self.highlighted) {

NSLog(@"highlighted");

UIColor*color = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"button"]];

UIColor*cl = [colorcolorWithAlphaComponent:0.9f];

[selfsetBackgroundColor:cl];

}else{

NSLog(@"normal");

UIColor*color = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"button"]];

UIColor*cl = [colorcolorWithAlphaComponent:1.0f];

[selfsetBackgroundColor:cl];

}

}else{

NSLog(@"no enabled");

UIColor*color = [UIColorcolorWithRGBString:@"#D8D9DD"];

[selfsetBackgroundColor:color];

}

}

但后来又有需求要修改其title,用setTitle的方法总不奏效,

后来研究发现,重写了setNeedsLayout方法后,无法再设置title,

就用KVO解决了

-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context{

//int age = [[change objectForKey:@"new"] intValue];

//self.ageLabel.text = [NSString stringWithFormat:@"%d",age];

BOOLmyEnable = [[changeobjectForKey:@"enabled"]boolValue];

NSLog(@"myEnable = %d",myEnable);

if(self.enabled) {

UIColor*color = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"button"]];

UIColor*cl = [colorcolorWithAlphaComponent:1.0f];

[selfsetBackgroundColor:cl];

[selfsetTitle:@"enable"forState:UIControlStateNormal];

}else{

UIColor*color = [UIColorcolorWithRGBString:@"#D8D9DD"];

[selfsetBackgroundColor:color];

[selfsetTitle:@"unEnable"forState:UIControlStateNormal];

}

}

你可能感兴趣的:(button奇葩问题解决)