2011-12-08 28 views
0

創建亮狀態的背景圖像編程我創建了一個UIBarButton編程用下面的代碼:爲UIButton的

UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];  
[rightButton setFrame:CGRectMake(0, 0, 81, 30)]; 
[rightButton setBackgroundColor:[UIColor clearColor]];  
rightButton.layer.borderColor = [UIColor blackColor].CGColor; 
rightButton.layer.borderWidth = 0.5f; 
rightButton.layer.cornerRadius = 5.0f; 
rightButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12]; 
[rightButton setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; 
[rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
//set text according to sign in status 
if (signIn) { 
    [rightButton setTitle:@"5 votes left" forState:UIControlStateNormal]; 
} else { 
    [rightButton setTitle:@"Sign in" forState:UIControlStateNormal]; 
} 

UIBarButtonItem * rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton]; 
self.navigationItem.rightBarButtonItem = rightBarButton; 

得到的按鈕有希望的方面,但現在我需要的是,當按鈕的狀態突出應該有漸變效果漸變爲黑色,以讓用戶知道他已按下按鈕,因爲現在當我按下按鈕時,視圖沒有任何反應,因此用戶無法知道他已按下按鈕。

我想探索一個選擇,不涉及爲所需的狀態設置背景圖像,因爲按鈕的文本可以根據應用程序配置dinamically更改,所以我需要完全通過代碼完成此操作。我真的不知道如何解決這個問題,所以任何幫助都很樂意接受。

回答

0

Although this won't directly answer your question, it may help.我不得不動態地爲按鈕創建一些圖形,並想出了一種使用核心圖形來創建我的按鈕圖像的方法。它使我可以靈活地在代碼中以參數方式更改外觀。它在抽象圖形上下文中繪製按鈕圖像,然後將結果轉換爲可用於按鈕的圖像。 YOu可能會從我的解釋中得到足夠的信息,您可以自己嘗試以滿足您的需求。

0

子類UIButton並添加CALayer或CAGradientLayer以實現所需的突出顯示效果。將高亮圖層的初始狀態設置爲隱藏狀態。用類似的東西替代setHighlighted:

- (void) setHighlighted:(BOOL)highlight { 
    highlightLayer.hidden = !highlight; 
    [super setHighlighted:highlight]; 
}