我有一个UIButton,此按钮从xib加载子视图。一切都绘制良好,并且正确调用了委托方法,但是没有突出显示效果。
我将xib上的所有内容都设置为userInteractionEnabled = false。如果删除这些子视图,则突出显示效果将再次起作用。
如果所有子视图碰巧都是图像,则有一个疯狂的解决方案:创建多个UIButton作为子视图,并将其高亮/禁用状态绑定在一起。将它们全部添加为主按钮的子视图,禁用用户交互,并在主按钮上使用K-V观察器。这是一个简单的例子:
// Only perform the addObserver part if from a XIB
- (UIButton *) makeMasterButton {
// Create some buttons
UIButton *masterButton = [UIButton buttonWithType:UIButtonTypeCustom];
masterButtonFrame = CGRectMake(0,0,100,100);
UIButton *slaveButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
slaveButton1.userInteractionEnabled = NO;
[slaveButton1 setImage:[UIImage imageNamed:@"Top.png"]];
slaveButton1.frame = CGRectMake(0, 0,100,50);
[masterButton addSubview:slaveButton1];
UIButton *slaveButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
slaveButton2.userInteractionEnabled = NO;
[slaveButton2 setImage:[UIImage imageNamed:@"Bottom.png"]];
slaveButton2.frame = CGRectMake(0,50,100,50);
[masterButton addSubview:slaveButton2];
// Secret sauce: add a K-V observer
[masterButton addObserver:self forKeyPath:@"highlighted" options:(NSKeyValueObservingOptionNew) context:NULL];
[masterButton addObserver:self forKeyPath:@"enabled" options:(NSKeyValueObservingOptionNew) context:NULL];
return masterButton;
}
...
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([object isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)object;
for (id subview in button.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *buttonSubview = (UIButton *) subview;
buttonSubview.highlighted = button.highlighted;
buttonSubview.enabled = button.enabled;
}
}
}
}
[当我想为具有层,透明度和动态加载内容的UIButton创建一个“图像”时,我必须这样做一次。
您可以将您从xib加载的视图转换为UIImage,然后将该图像添加到UIButton。这样,按下按钮时将显示高亮显示:
UIButton *button;
UIGraphicsBeginImageContext(viewFromXib.frame.size);
[viewFromXib.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[button setImage:image forState:UIControlStateNormal];