我已经向UITableViewCell的每一行添加了三个UIButtons。
当我选择一个UIButton时,它的颜色会变成黑色。问题是这些颜色的变化会影响到表格中其他单元格的按钮,我只是在表格中向下滚动时才看到的。
此链接还解释了相同的问题->UITableviewcell content updating reflects to other cell
我在iOS中找不到这个问题的任何答案。
这是我的cellForRowAtIndexPath
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"custCell"];
UIButton *btn1=[cell viewWithTag:101];
btn1.imageView.contentMode = UIViewContentModeScaleAspectFit;
[btn1 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
btn1.backgroundColor=[UIColor clearColor];
[btn1 setTag:(indexPath.row*3)+1];
UIButton *btn2=[cell viewWithTag:102];
btn2.imageView.contentMode = UIViewContentModeScaleAspectFit;
[btn2 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
btn2.backgroundColor=[UIColor clearColor];
[btn2 setTag:(indexPath.row*3)+2];
UIButton *btn3=[cell viewWithTag:103];
btn3.imageView.contentMode = UIViewContentModeScaleAspectFit;
[btn3 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
btn3.backgroundColor=[UIColor clearColor];
[btn3 setTag:(indexPath.row*3)+3];
rerutn cell;这是我的按钮操作方法
- (IBAction)btnClicked:(id)sender
{
UIButton *button=(UIButton *)sender;
NSLog(@"tag %ld",(long)button.tag);
if(button.backgroundColor==[UIColor blackColor]){
button.backgroundColor=[UIColor clearColor];
}
else if(button.backgroundColor==[UIColor clearColor]){
button.backgroundColor=[UIColor blackColor];
}
}这段代码没什么新意。我怎样才能以编程方式解决这个问题。谢谢你..!
发布于 2016-05-02 17:41:26
替换
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"custCell"];使用
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"custCell" forIndexPath:indexPath];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"custCell"];
}希望它能有所帮助:)
发布于 2016-07-20 17:31:14
制作UITableViewCell并添加UIButton,并使用故事板对它们进行标记。
@interface TblCellCategoryCell:UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;
@end发布于 2016-05-02 17:40:21
这是因为UITableView重用了单元格,而不是创建新单元格。因此,假设您更改了索引为2的单元格的颜色,因此每当UITableView重用该单元格时,它都会显示先前创建的具有更改颜色按钮的单元格。
对于您的特定问题,您总是重置按钮的标签,因此下次您尝试从viewWithTag获取按钮时,它将不会返回任何按钮,或者返回错误的按钮。
https://stackoverflow.com/questions/36979054
复制相似问题