0

私はUITableView20行あります。各行に2つUIButtonのが追加されているので、合計で40個のボタンがあります。各セルの各ボタンにアクセスするにはどうすればよいですか?それらUIButtonはすべて2つtagのs1と2を持っています。

例:特定の行の2つのボタンの背景色を変更するメソッドを作成します。

-(void)changeColor:(int)row{
     //code here
}

何か提案はありますか?

-(UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:@"Cell"] autorelease];
        UIButton *button1=[[UIButton alloc] initWithFrame:CGRectMake(x1,y1,w1,h1)];
        UIButton *button2=[[UIButton alloc] initWithFrame:CGRectMake(x2,y2,w2,h2)];       
        [button1 setTag:1];
        [button2 setTag:2];
        [[cell contentView] addSubview:button0 ];
        [[cell contentView] addSubview:button1 ];
        [button0  release];
        [button1  release];        
    }
    UIButton *button1  = (UIButton *)[cell viewWithTag:1];
    UIButton *button2  = (UIButton *)[cell viewWithTag:2];
    return cell;
}
4

2 に答える 2

1

あなたはこれを行うことができるはずです:

-changeColor:(int)row
{
    NSIndexPath indexPath = [NSIndexPath indexPathForRow:row inSection:0]; // Assuming one section
    UITableViewCell *cell = [myTableView cellForRowAtIndexPath:indexPath];

    UIButton *button1 = (UIButton *)[[cell contentView] viewWithTag:1];
    UIButton *button2 = (UIButton *)[[cell contentView] viewWithTag:2];
}

*一部の構文が間違っている可能性があります。Xcodeが手元にありません

于 2012-12-04T21:18:26.683 に答える
0

ボタンの色を変更してハイライト/ダウンステートにする場合は、次を使用することをお勧めします。

[yourButton addTarget:self action:@selector(goToView:) forControlEvents:UIControlEventTouchUpInside];
[yourButton addTarget:self action:@selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self action:@selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];

-(void)buttonAction:(UIButton*)sender
{
    [self touchCancel:sender];
    /* DO SOME MORE ACTIONS */
}

-(void)changeColor:(UIButton*)sender
{
    sender.backgroundColor = [UIColor redColor];
}

-(void)touchCancel:(UIButton*)sender
{
    sender.backgroundColor = [UIColor clearColor];
}

ボタンの色を選択したい場合は、選択したすべての状態を保持する配列を作成します。次に、配列を使用して、cellForRowAtIndexPathでボタンの色に別の色が必要かどうかを確認します。

ボタンの色を変更したい場合は、配列の値を変更して呼び出します

[self.tableView reloadData];

必ずif(cell == nil)メソッドの外で実行して、セルが再利用されるときにも呼び出されるようにしてください。

于 2012-12-05T12:22:44.170 に答える