ios - UITableViewCell 的条件背景色

标签 ios objective-c xcode uitableview colors

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

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

最佳答案

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

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

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

- (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];
}

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

关于ios - UITableViewCell 的条件背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346336/

相关文章:

ios - ACAccountType 始终显示 0 个帐户

ios - UITableViewCell 中的自动布局标签和图像

iphone - Xcode自动将对象转换为NSArray

ios - 在 isEqual 中测试 NSNumber 是否为 nil

objective-c - 除了已知的之外,Objective-c 中类扩展的其他用途

ios - 接口(interface)生成器 "view - image view"关系

ios - ObjectMapper如何映射[String :CustomObject] With Index as CustomObject Property的Dictionary

支持服务器的 iOS 9 ATS SSL 错误

ios - 执行 war 的最大重试次数。应用程序加载器问题

swift - "Self captured by enclosure before all members were initialized"使用 Alamofire 和 SwiftyJSON