表格在桌面视图滚动中查看自定义单元格按钮颜色和标题更改

时间:2016-04-13 06:09:46

标签: objective-c

我有自定义单元格的表格视图,其中一个按钮具有红色并带有标题验证,点击它会变为绿色,标题为Experience.But问题是当我滚动未点击的按钮变为绿色时带有头衔经验

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

     static NSString *CellIdentifier = @"Cell1";



    BoastsMainCell1 *cell1 =
    (BoastsMainCell1*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];






    cell1.selectionStyle = UITableViewCellSelectionStyleNone;

    if(cell1 == nil) {
        cell1 = [[BoastsMainCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];


    }


    [cell1.verifyBnt addTarget:self action:@selector(verifyButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

return cell1;
}



-(void)verifyButtonClicked:(UIButton*)sender
{




    [sender setTitle:@"Experience" forState:UIControlStateNormal];
    sender.backgroundColor=[UIColor greenColor];




}

3 个答案:

答案 0 :(得分:0)

你应该像下面那样重置单元格状态:

    if(cell1 == nil) {
        cell1 = [[BoastsMainCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
//it's just a example. some code like this to reset the UI element.
//    [cell1.verifyBnt setSelected:NO];
//    [cell1 updateCell.....

原因是该细胞将被重复使用。

答案 1 :(得分:0)

BoastsMainCell1课程中,您应该覆盖- (void)prepareForReuse。发生的事情是操作系统正在重用一个单元格,你应该重置它的属性。 prepareForReuse是你重置的机会。

From Apple's documentation:

  

如果UITableViewCell对象是可重用的 - 也就是说,它具有重用性   identifier - 在返回对象之前调用此方法   来自UITableView方法dequeueReusableCellWithIdentifier:。对于   性能原因,你应该只重置那个单元格的属性   与内容无关,例如,alpha,编辑和选择   州。 tableView中的表视图委托:cellForRowAtIndexPath:   重复使用单元格时应始终重置所有内容。如果是细胞   对象没有关联的重用标识符,此方法是   不叫。如果重写此方法,则必须确保调用   超类实现。

在您的实施文件BoastsMainCell1.m中,您可以添加类似于此的方法:

  - (void)prepareForReuse {
        [super prepareForReuse];
        self.backgroundColor = [UIColor redColor];
    }

答案 2 :(得分:0)

你有一个误解,一个TableViewCell将保留其视图的状态。但它绝对错了。也就是说,滚动tableview时将重用TableViewCell,重用的单元格将使用默认的UI状态。在您的情况下,您必须在单元格之外保持按钮的“选定”状态,就像ViewController类中的Dictionary一样。例如,当您从按钮获取事件时,将该状态存储在字典中。在'cellForRowAtIndexPath'方法中,您必须检查当前行是否已从此字典中选择状态并设置适当的颜色值,例如

if (dict[@(indexPath.row)] == @(YES)) {
    //Set red color
} else {
   //green color
}

请注意,这可能不是完美的方式。唯一的目的是让您了解细胞将如何重复使用以及如何保留细胞状态。

相关问题