【问题标题】:Conditional background color for UITableViewCellUITableViewCell 的条件背景颜色
【发布时间】:2014-04-16 06:45:21
【问题描述】:

我正在尝试为子类UITableViewCell 设置背景颜色。我知道通常我应该使用tableView:willDisplayCell:forRowAtIndexPath:。但是,我有一些逻辑可以自定义tableView:cellForRowAtIndexPath:UITableViewCell 的几个方面,我想根据该逻辑设置单元格的背景颜色。我是否必须在tableView:cellForRowAtIndexPath: 中复制tableView:willDisplayCell:forRowAtIndexPath: 中的全部条件才能设置背景颜色?这种代码重复似乎很浪费,而且可能是不明智的。

我能想到的最佳解决方案是将 UIColor 属性添加到 UITableViewCell 子类,根据那里的条件将其设置在 tableView:cellForRowAtIndexPath: 中,然后让 tableView:willDisplayCell:forRowAtIndexPath: 将单元格的背景颜色设置为自己的颜色财产。这是处理这种情况的正确方法吗?它看起来有点笨拙,但我想不出更好的方法。

【问题讨论】:

    标签: ios objective-c xcode uitableview colors


    【解决方案1】:

    您可以创建返回适当颜色的函数并进行相应的设置

    -(UIColor*)getColorForIndexPath:(NSIndexPath*){
        UIColor *cellColor=nil;
        //Do whatever your logic is for finding appropriate color assign to cellColor
        return cellColor;
    }
    

    现在使用这个函数来设置颜色为,所以你只需要修改一个地方就可以在两个地方生效。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        .... //Your code for cell
    
        cell.backgroundColor = [self getColorForIndexPath:indexPath];
    }
    
    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
        .... //Your code for cell
    
        cell.backgroundColor = [self getColorForIndexPath:indexPath];
    }
    

    注意:如果您只放置在任何委托方法上,这仍然有效,因此无需在 2 个地方调用。

    【讨论】:

    • 这只是移动到重复代码所在的位置。我在tableView:cellForRowAtIndexPath: 中有条件逻辑,它自定义了单元格的其他几个方面,我试图避免将这些条件复制到另一个方法中,只是为了设置背景颜色
    • 不,我想知道这里是否有避免代码重复的好方法。此解决方案会导致代码重复,因为决定如何自定义单元格(包括背景颜色)的条件逻辑需要出现在 tableView:cellForRowAtIndexPath: 中,用于标签文本和按钮功能等内容,并且再次出现在 getColorForIndexPath: 函数中建议选择合适的背景颜色。
    猜你喜欢
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多