質問

I am making an iOS app and it has a Table View with prototype cells. I configure the cells in the cellForRowAtIndexpath method and that works fine, but where I come into trouble is when I want to change the text in the button after it was created. I want it so that it changes the button text when I tap the button. I tried to do:

[button setTitle:@"Change" forState:UIControlStateNormal];

inside of the clickMethod that runs when I click the the button, but it changes the text in the last cell no matter which button I press. What I tried above doesn't work because I have multiple instances of the same button.(one in every row) So does anybody know how I can change the text of the button I click on only. Code that creates the button:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
//configure cell
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(clickMethod:) forControlEvents:UIControlEventTouchUpInside];


[button setTitle:@"Button" forState:UIControlStateNormal]
[button setTag:6789];//set tag so we can identify the button
button.Frame=CGRectMake(218, 5, 99, 53);
[cell addSubview:button];//put the button in the cell
[cell setIndentationWidth:45];
[cell setIndentationLevel:1];
return cell;//return the cell object

Help is greatly appreciated. I can post more code, however I don't believe that will be relevant to the question. Thanks in advance.

役に立ちましたか?

解決

You can't set title on button as cellForRowAtIndexPath: method calls multiple times. If button is globally declared it will change title for last button. Just do like that

-(void)clickMethod:(id)sender
{
    [sender setTitle:@"Change" forState:UIControlStateNormal];
}

sender will have the instance of clicked button.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top