2012-12-30 74 views
14

我有一種方法可以創建一個自定義UIButton,使我可以使用QuartzCore更改按鈕的顏色。但按鈕在被觸摸時不會突出顯示。自定義UIButton觸摸時不突出

- (UIButton *)makeHeaderButton { 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    UIFont *textFont = [UIFont boldSystemFontOfSize:12]; 
    UIColor *textColor = [UIColor colorWithRed:80/255.0 green:109/255.0 blue:145/255.0 alpha:1.0]; 
    UIColor *backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0]; 
    [button setTitleColor:textColor forState:UIControlStateNormal]; 
    button.titleLabel.font = textFont; 
    button.autoresizesSubviews = YES; 
    button.layer.cornerRadius = 8; 
    button.layer.borderWidth = 1; 
    // next 2 properties set using QuartzCore class, no other way to set button colors 
    button.layer.borderColor = [UIColor grayColor].CGColor; 
    button.layer.backgroundColor = backgroundColor.CGColor; 
    button.clipsToBounds = YES; 
    return button; 
} 

如何讓這些按鈕像普通的圓形按鈕一樣突出顯示?

回答

13

在你的代碼,添加行button.showsTouchWhenHighlighted = TRUE;

+1

這似乎只是使標題淡出和進入。我希望當按鈕被觸摸時,按鈕背景會閃爍爲藍色。 – Bob

+1

@Bob你總是可以設置手動高亮顯示。例如:註冊一個事件'onTouchDown'(或任何它),然後在實現中做一些事情''button.layer.backgroundColor = [UIColor BlueColor];'然後'onTouchUp'改變顏色回到您的設置 – Garrett

+5

哇,這變得越來越複雜。我想要做的就是製作一個具有自定義背景色的RoundRect按鈕。當然有一個更簡單的方法來做到這一點。 – Bob

-4

在故事板設置按鈕的背景默認的圖像和突出顯示的圖像。 上的按鈕進行操作在此線即改變按鈕顏色1秒鐘

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]]; 
-1

還有就是要實現自定義按鈕高亮簡單的方法。 1.創建高亮狀態的.png圖像(帶顏色,alpha等); 2.轉到yourbutton.xib; 3.選擇XCode右側的Attributes Inspector; 4.設置狀態配置爲高亮 5.將.png圖像設置爲背景圖像。 歡迎您:)

5

如果有人仍然遇到問題 - 你應該這樣創建的UIButton:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; 

btn.layer.cornerRadius = 4; 
btn.layer.masksToBounds = YES; 

[btn setTranslatesAutoresizingMaskIntoConstraints:NO]; 

[btn setBackgroundColor:[UIColor greenColor]]; 
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 

[btn setTitle:@"ok" forState:UIControlStateNormal]; 

*** any customisation that you would like *** 

[parentView addSubview: btn]; 

所以這樣你還有iOS版採取一切高亮的照顧。最主要的是使用

[UIButton buttonWithType:UIButtonTypeSystem]; 

如果使用initWithFrame或任何其他方法 - 你將不得不實施

setTitleColor: forState: 
setBackgroundImage: forState: 
+2

使用系統按鈕與自定義按鈕是關鍵,即使按鈕是在故事板或筆尖上創建的,在IB中設置按鈕上的圖像將其更改爲自定義按鈕,因此您需要手動將其更改回來。 –

2

您可以創建自己的UIButton子類(那麼你只需設置在所有放入系統性能構造函數)。

而且必須覆蓋的UIButton

- (void)setHighlighted:(BOOL)highlighted { 
    if (highlighted) { 
     self.backgroundColor = [UIColor redColor]; 
    } else { 
     self.backgroundColor = [UIColor blueColor]; 
    } 
} 
0

亮點方法對於斯威夫特,創建一個從UIButton繼承的自定義類並覆蓋isHighlighted屬性:

class ButtonWithHighlight: UIButton { 

    override var isHighlighted: Bool { 
     get { 
      return super.isHighlighted 
     } 
     set { 
      if newValue { 
       backgroundColor = <#color when highlighted#> 
      } 
      else { 
       backgroundColor = <#color for normal state#> 
      } 
      super.isHighlighted = newValue 
     } 
    } 

}