【问题标题】:UIButton + XIB subviews = no highlightUIButton + XIB 子视图 = 没有高亮
【发布时间】:2011-12-12 07:52:05
【问题描述】:

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

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

【问题讨论】:

    标签: uibutton touch xib subview effect


    【解决方案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 制作“图像”时,我不得不这样做。

    【讨论】:

      【解决方案2】:

      您可以将从 xib 加载的视图转换为 UIImage,然后将该图像添加到 UIButton。这样当按钮被按下时,高亮就会显示出来:

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

      【讨论】:

        猜你喜欢
        • 2011-06-28
        • 2011-11-29
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多