I know there are a few posts abou this but I am still confused why the button i created in a tableview wont keep its state when its selected. When I scroll, unselected buttons get affected and it changes back and forth. Please help.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setTitle:@"Like" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
myButton.tag =indexPath.row;
[cell.contentView addSubview:myButton];
}
else{
[cell.contentView addSubview:myButton];
}
if ([array objectAtIndex:indexPath.row==0]) {
[myButton setTitle:@"Like" forState:UIControlStateNormal];
}
else{
[myButton setTitle:@"Unlike" forState:UIControlStateNormal];
}
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
return cell;
}
-(void)tapped:(UIButton *)sender {
if ([sender.currentTitle isEqualToString:@"Like"]) {
[sender setTitle:@"Unlike" forState:UIControlStateNormal];
[array replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithInt:1]];
}
else{
[sender setTitle:@"Like" forState:UIControlStateNormal];
}
}