2012-12-27 170 views
0

改變一個UIButton的顏色有一大堆UIButtons,其中一些需要根據情況來改變顏色的,它是目前像這樣處理的:基於其標籤

UIButton *button; 
button = [self.view viewWithTag:positionInArray]; 
[button setBackgroundColor:[UIColor cyanColor]]; 
button = [self.view viewWithTag:positionInArray-1]; 
[button setBackgroundColor:[UIColor cyanColor]]; 
button = [self.view viewWithTag:positionInArray+3]; 
[button setBackgroundColor:[UIColor cyanColor]] 
button = [self.view viewWithTag:positionInArray+4]; 
[button setBackgroundColor:[UIColor cyanColor]]; 

它的工作原理,但即設置一個按鈕,標籤代碼拋出了這樣的警告:

「不兼容的指針類型初始化‘的UIButton * __強’與‘的UIView *’類型的表達式」

我將如何去正確地這樣做呢?

+0

你可以投到(UIButton *),但它看起來仍然可以以更好的方式完成。 – Stavash

+0

我該怎麼做?我以前從來沒有涉足過這個問題,一個不會發出警告的解決方案至少比一個解決方案好,即使它不美觀。 –

回答

0

你需要投你UIViews到UIButtons這樣的:

button = (UIButton *)[self.view viewWithTag:positionInArray]; 

不過最好還是來驗證你的觀點實際上是按鈕來執行類似:

UIView *button = [self.view viewWithTag:positionInArray]; 
if ([button isKindOfClass[UIButton class]] { 
    [button setBackgroundColor:[UIColor cyanColor]]; 
} 

在這個例子中有沒有必要去UIButton,因爲UIViews也有這種方法。如果你只想改變UIButton的顏色,你只需要if語句。

1

問題是,viewWithTag:可能會返回UIView的任何子類。如果你知道它會返回一個UIButton肯定的,你可以施放它是這樣的:

button = (UIButton *)[self.view viewWithTag:positionInArray]; 

這將隱藏的警告,但可能會產生意想不到的結果時,認爲是不是一個按鈕!一個更好的解決辦法是檢查返回UIView子類是一個UIButton:

UIView *view = [self.view viewWithTag:positionInArray]; 
if ([view isKindOfClass:[UIButton class]]) { 
    button = (UIButton *)view; 
    [button setBackgroundColor:[UIColor cyanColor]]; 
} else { 
    NSLog(@"Ooops, something went wrong! View is not a kind of UIButton."); 
} 
1

的問題是,viewWithTag:返回UIView,因爲它可以是任何UIView子類,包括UIButton的。

這是設計相關的,如果沒有具有此標籤的任何其它子視圖,那麼你只需簡單地把結果轉換到一個UIButton像其他的答案,並用它:)

0

向下轉換完成替代方案

viewWithTag:返回一個UIView,但它可能指向UIView對象的任何子類。
由於多態性是有效的,並且消息是動態的,你可以這樣做:

UIView *button; 
button = [self.view viewWithTag:positionInArray]; 
[button setBackgroundColor:[UIColor cyanColor]]; 

您從UIView的繼承的backgroundColor,這樣就不會有任何問題。
但是,你總是可以使用類型id,這是一種「快活」。