如果你所有的子视图碰巧都是图像,有一个疯狂的解决方案:创建多个 UIButton 作为子视图并将它们的高亮/禁用状态绑定在一起。将它们全部添加为主按钮的子视图,禁用用户交互,并在主按钮上使用 KV 观察器。这是一个快速示例:
// 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我想为具有图层、透明度和动态加载内容的 UIButton 制作“图像”时,我不得不这样做一次。