首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >UITableviewcell内容更新反映了

UITableviewcell内容更新反映了
EN

Stack Overflow用户
提问于 2016-05-02 17:22:33
回答 4查看 82关注 0票数 1

我已经向UITableViewCell的每一行添加了三个UIButtons

当我选择一个UIButton时,它的颜色会变成黑色。问题是这些颜色的变化会影响到表格中其他单元格的按钮,我只是在表格中向下滚动时才看到的。

此链接还解释了相同的问题->UITableviewcell content updating reflects to other cell

我在iOS中找不到这个问题的任何答案。

这是我的cellForRowAtIndexPath

代码语言:javascript
复制
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;

这是我的按钮操作方法

代码语言:javascript
复制
- (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];
    }
}

这段代码没什么新意。我怎样才能以编程方式解决这个问题。谢谢你..!

EN

回答 4

Stack Overflow用户

发布于 2016-05-02 17:41:26

替换

代码语言:javascript
复制
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"custCell"];

使用

代码语言:javascript
复制
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"custCell" forIndexPath:indexPath];

        if (cell == nil){

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"custCell"];
        }

希望它能有所帮助:)

票数 1
EN

Stack Overflow用户

发布于 2016-07-20 17:31:14

制作UITableViewCell并添加UIButton,并使用故事板对它们进行标记。

代码语言:javascript
复制
@interface TblCellCategoryCell:UITableViewCell

@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;

@end
票数 1
EN

Stack Overflow用户

发布于 2016-05-02 17:40:21

这是因为UITableView重用了单元格,而不是创建新单元格。因此,假设您更改了索引为2的单元格的颜色,因此每当UITableView重用该单元格时,它都会显示先前创建的具有更改颜色按钮的单元格。

对于您的特定问题,您总是重置按钮的标签,因此下次您尝试从viewWithTag获取按钮时,它将不会返回任何按钮,或者返回错误的按钮。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36979054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档