如何检测tableview单元格中的多个按钮,我的疑问是示例,如果我点击一个按钮,该按钮将改变颜色,并且如果我单击indexpath.row = 1该按钮将变色的单元格按钮,则单元格中将有3个按钮改变帮助我
我确实是这样的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10.0, 0.0, self.tableView.frame.size.width/4, 40.0);
button.tag = 100 + indexPath.row*total_buttons_in_a_row;
[button setTitle:[NSString stringWithFormat:@"%ld",(long)button.tag] forState:UIControlStateNormal];
[button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button2.frame = CGRectMake(10.0+self.tableView.frame.size.width/4+10.0, 0.0, self.tableView.frame.size.width/4, 40.0);
button2.tag = 100 + indexPath.row*total_buttons_in_a_row + 1;
[button2 setTitle:[NSString stringWithFormat:@"%ld",(long)button2.tag] forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button2];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button3.frame = CGRectMake(10.0+self.tableView.frame.size.width/4*2+10.0, 0.0, self.tableView.frame.size.width/4, 40.0);
button3.tag = 100 + indexPath.row*total_buttons_in_a_row + 2;
[button3 setTitle:[NSString stringWithFormat:@"%ld",(long)button3.tag] forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button3];
return cell;
}
-(void)btnClicked:(UIButton *)sender{
id selectedButton = [self.view viewWithTag:sender.tag];
if ([selectedButton backgroundColor] == [UIColor redColor]) {
[selectedButton setBackgroundColor:[UIColor clearColor]];
}else{
[selectedButton setBackgroundColor:[UIColor redColor]];
}
}
total_buttons_in_a_row
是一个Int
。在你的情况下定义它viewDidLoad
total_buttons_in_a_row=3
PS-CGRectMake
根据您的需要设置按钮。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句