1

CustomCellで作成したボタンがあります。

- (IBAction)onoffBtn:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    if (button.selected)
    {
        // Do action 1
    }
    else
    {
        // Do action 2
    }
}

実行すると、TableViewControllerで作成したUITableView内のセルにボタンが表示されます。セル内でそのonoffBtnを押すことはできますが、アクションを実行できません。ボタンがアクションを実行できるようにするにはどうすればよいですか?

これは、TableViewController.m内のcellForRowAtIndexPathです。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier]];
    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = _customCell;
        _customCell = nil;
    }
    // Show my cell
    return cell;
}

そして他の質問のために、私はどこでプロセスを行うために書くべきですか?TableViewController.mまたはCustomCell.mの内部ですか?よろしければ、コードと説明を教えてください。ここで新しく、まだ学習中です。私はあなたが書くコードのすべての行で理解したいです。ありがとうございました。

アップデート:

これは、これまでのTableViewController.m内の私のcellForRowAtIndexPathです。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier]];
    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = _customCell;
        _customCell = nil;
    }
    button.tag = indexPath.row;
    cell.titleLabel.text = [titleArray objectAtIndex:indexPath.row];
    cell.timerLabel.text =  [timeArray objectAtIndex:indexPath.row];
    time = [[secondArray objectAtIndex:indexPath.row] integerValue];
    NSLog(@"Title %@, time %@, second %@, time %i, tag %d", titleArray, timeArray, secondArray, time, button.tag);
    return cell;
}

そしてこれはログによると:

2012-08-04 17:38:36.257 Table[1269:f803] Title (
    "Test 1",
    "Test 2"
), time (
    "10 secs",
    "5 secs"
), second (
    10,
    5
), time 10, tag 0 // tag 0 for cell 1
2012-08-04 17:38:36.261 Table[1269:f803] Title (
    "Test 1",
    "Test 2"
), time (
    "10 secs",
    "5 secs"
), second (
    10,
    5
), time 5, tag 0 // tag should be 1 for cell 2 but it said 0. How to fix it?
4

1 に答える 1

1

これは、セル内のアクションでボタンを追加する方法です

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

// ADDING A BUTTON WITH TARGET
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundRect];
btn.frame = CGRectMake(0, 0, 50, 50);
btn.showsTouchWhenHighlighted = YES;
btn.tag = indexPath.row;
[btn addTarget:self action:@selector(onoffBtn:) forControlEvents:UIControlEventTouchUpInside];

[cell.contentView addSubview:btn];

return cell;
}


- (IBAction)onoffBtn:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
if (button.selected)
{
    // Do action 1
}
else
{
    // Do action 2
}
}
于 2012-08-04T07:56:06.410 に答える