2011-10-21 78 views
2

我有一個UIButton,並且此按鈕從xib加載子視圖。 一切都很好,委託方法被正確調用,但沒有突出顯示效果。UIButton + XIB子視圖=無高亮

我將xib集上的所有內容都設置爲userInteractionEnabled = false。 如果我刪除這些子視圖,高亮效果將再次起作用。

任何幫助將不勝感激。

回答

2

您可以將您從xib加載的視圖轉換爲UIImage,然後將該圖像添加到UIButton中。這種方法是按下按鈕時的亮點將顯示:如果所有子視圖恰巧是圖像

UIButton *button; 

UIGraphicsBeginImageContext(viewFromXib.frame.size); 
[viewFromXib.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
[button setImage:image forState:UIControlStateNormal]; 
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是有層,透明和動態加載內容的「形象」。