2015-07-20 50 views
0

我有6個按鈕放置在一個視圖,並試圖相應地改變的backgroundColor:迭代通過按鈕sender.superview

- (IBAction)btnPressed:(UIButton *)sender { 
    for(UIButton *btn in sender.superview){ 
     [btn setBackgroundColor:[UIColor whiteColor]]; 
    } 
    [sender setBackgroundColor:[UIColor blackColor]]; 
} 

以下錯誤消息: [UIView的countByEnumeratingWithState:對象:計數:]:無法識別的選擇發送到實例0x174191d30 2015-07-20 17:12:00.853 Raymio [20370:2209236] ***由於未捕獲異常'NSInvalidArgumentException',原因:' - [UIView countByEnumeratingWithState:objects:count:]:無法識別的選擇器已發送到實例0x174191d30'

我得到一個編譯器警告警報這可能會發生,但我是不是正確得到發件人這樣的superview?

編輯:也許我誤解了某事。我有一個視圖控制器(主視圖obv)。在那個vc中,我有很多意見,包括一個視圖,我有6個按鈕。我想在那個特定視圖只有6個按鈕,所以我試圖讓發送方的上海華,以爲我得到了我用來放置6個按鈕在視圖中。

+0

嗯,喲你無法遍歷單個視圖? –

+0

@davidcao我不知道這是否意味着修辭或什麼。無論如何,我在一個視圖中迭代x個按鈕的數量? – DevilInDisguise

回答

1

枚舉子視圖確保你參考子視圖數組:

for (UIButton *btn in sender.superview.subviews) { 

    if ([btn isKindOfClass:[UIButton class]]) { 
     [btn setBackgroundColor:[UIColor whiteColor]]; 
    } 
} 
+0

hm,是否有必要發送isKindOfClass方法,因爲for只是循環遍歷UIButton的呢? – DevilInDisguise

+1

@DevilInDisguise如果你確定唯一的子視圖是'UIButton'對象,那麼不是,它根本就不是。我只是不確定您的視圖是否包含其他視圖類型,並導致另一次意外崩潰。 – thattyson

+0

你的帖子是否在頂部意思是它遲到或早期回答:)?.. – DevilInDisguise

0

sender.superview不符合NSFastEnumeration protocol。也許你想遍歷sender.subviews(或sender.superview.subviews),如:

- (IBAction)btnPressed:(UIButton *)sender { 
    for(UIButton *btn in sender.subviews){ 
    [btn setBackgroundColor:[UIColor whiteColor]]; 
    } 
    [sender setBackgroundColor:[UIColor blackColor]]; 
} 

編輯:

就像我說的,你可以用你的按鈕限定出口集:

@property(nonatomic, strong) IBOutletCollection(UIButton) NSArray *buttons; 

創建這些按鈕,此數組中添加它們(或通過界面生成器連接),然後執行下一個:

- (IBAction)btnPressed:(UIButton *)sender { 
    for(UIButton *btn in buttons){ 
    [btn setBackgroundColor:[UIColor blackColor]]; 
    } 
    [sender setBackgroundColor:[UIColor whiteColor]]; 
} 
+0

獲取按鈕的子視圖是否有意義?我的按鈕沒有任何(子)視圖。 – DevilInDisguise

+0

我會建議使用IBOutletCollection定義按鈕的出口集合並迭代這個集合。如果對象等於發件人 - 將背景顏色設置爲黑色。如果不是 - 將其設置爲白色。 – sgl0v