UIButton + XIB subviews =无突出显示

时间:2011-10-21 05:54:26

标签: uibutton touch xib effect subviews

我有一个UIButton,这个按钮从xib加载子视图。 一切都很好,委托方法被正确调用,但没有高亮效果。

我将xib上的所有内容设置为userInteractionEnabled = false。 如果我删除这些子视图,高亮效果会再次起作用。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以将从xib加载的视图转换为UIImage,然后将该图像添加到UIButton中。这样,按下按钮时将显示突出显示:

UIButton *button;

UIGraphicsBeginImageContext(viewFromXib.frame.size);
[viewFromXib.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[button setImage:image forState:UIControlStateNormal];

答案 1 :(得分:1)

如果您的所有子视图都恰好是图片,那么就会有一个疯狂的解决方案:创建多个UIButtons作为子视图,并将其突出显示/禁用状态绑定在一起。将它们全部添加为主按钮的子视图,禁用用户交互,并在主按钮上使用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创建“图像”时,我不得不这样做。