2016-05-13 6 views
0

私はUIButtonオブジェクトで構成されたボタンという配列を持っています。次のように入力します。NSMutableArrayのUIButtonオブジェクトのメソッドを呼び出すObjective-C

for (int i=0; i<self.numButtons; i++) { 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; 
    [button setTitle:@"Title" forState:UIControlStateNormal]; 
    button.frame = CGRectMake(xCoord-40, y, 80, 20); 
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; 
    [button setTag:i]; 
    [self.buttons addObject:button]; 
    [self.view addSubview:button]; 
    y+= 45; 
} 

これらのボタンの動作はbuttonActionです。このアクションは、選択されたボタンの色を変更するはずです。ここに私はそれをどのように実装したのですか:

-(void) buttonAction:(id)sender{ 
    int num = (int)[sender tag]; 
    [[self.buttons objectAtIndex:num] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    NSLog(@"%@", [self.buttons objectAtIndex:buttonClicked].titleLabel.text); 
} 

色の変化はありません。ボタンのタイトルをNSLogにしようとしても、nullを返します。だから私の質問は、私はこれを修正することができるだけでなく、配列内のオブジェクトのメソッドを呼び出す方法ですか?どんな助けもありがとう。ありがとう!

+0

'self.buttons'はおそらく' nil'です。 – rmaddy

答えて

4

self.buttonsのすべての証拠点はnilです。これを初期化しましたか?あなたはbuttonAction:方法にsenderパラメータを使用することができますもちろん

self.buttons = [NSMutableArray array]; 

- (void)buttonAction:(UIButton *)button { 
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
} 

注パラメータの変化

どこかは次のような行が必要です。

+0

ありがとう!私はそれを初期化するのを忘れていたと信じることはできません – John55

+0

あなたはその間違いを犯す最初の人ではありません。しかし、他の場所でボタンにアクセスする必要がない限り、配列は必要ありません。 – rmaddy

+0

@rmaddyが正しいです。 UIViewは、サブビューとして追加されたすべてのUI要素のコレクションを保持します。ビューのすべての要素を取得するには、ビューコントローラ内からself.view.subviewsを簡単に呼び出します。 –

0

私はこれを行うのが好きです。 IBActionを使用することを忘れないでください。ペン先やストーリーボードを使用することを決めた場合に役立ちます。

-(IBAction) buttonAction:(id)sender{ 
    [((UIButton*)sender) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] 
    NSLog(@"%@", ((UIButton*)sender).titleLabel.text) 
} 
関連する問題