【问题标题】:UILabel backgroundColor in UITableViewCell always reverts to initial valueUITableViewCell 中的 UILabel backgroundColor 总是恢复为初始值
【发布时间】:2010-10-05 17:08:59
【问题描述】:

在我的应用程序中,我有一个 UITableViewCell 用于显示背景颜色设置。在 detailTextLabel 中,它显示颜色的名称,背景设置为实际颜色,例如[UIColor cyanColor]。请注意,我只设置了 detailTextLabel 的背景,而不是整个 UITableViewCell。当用户点击单元格时,他们会被带到另一个 UITableView,让他们选择一种颜色,当他们返回之前的 UITableView 时,UILabel 的 backgroundColor 会更新为新颜色。

问题是,每当我返回到初始 UITableView 时,UILabel 的 backgroundColor 会立即更新,然后返回到初始颜色。我不知道为什么它会恢复。有什么建议吗?

谢谢!

【问题讨论】:

  • 没有来源很难说,但我猜你的 cellForRowAtIndexPath 被调用并将你的单元格恢复到初始状态。

标签: iphone uitableview ios4 uilabel uicolor


【解决方案1】:

一些基于状态的属性由表视图设置;我相信背景颜色就是其中之一。换句话说,表格视图正在改变detailTextLabel 的背景颜色,这可能是取消突出显示选择的一部分。

在表格视图设置基于状态的属性后,表格委托有最后机会更新每个单元格的外观。这是在委托的tableView:willDisplayCell:forRowAtIndexPath: 方法中完成的。也许如果您在此方法中设置detailTextLabel 的背景颜色,您的问题就会消失。

【讨论】:

    【解决方案2】:

    当 cellForRowAtIndexPath 执行时,它通常会创建并返回一个新单元格。

    根据您的问题,不清楚您是否正在重新创建单元格,但如果是,这可以解释您描述的行为。

    【讨论】:

      【解决方案3】:

      是的..也许您没有在 cellForRowAtIndexPath 方法中重复使用您的单元格。 如果是,请尝试重复使用您的单元格,而不是每次都创建新单元格。

      【讨论】:

        【解决方案4】:

        我解决这个问题的方法是创建一个名为 HighlightedLabel 的 UILabel 子类,它具有以下初始化程序:

        - (id)initWithHighlightedBackgroundColor:(UIColor *)highlightedBackgroundColor nonHiglightedBackgroundColor:(UIColor *)nonHighlightedBackgroundColor
            {
                self = [super init];
                if(self)
                {
                    _highlightedBackgroundColor = highlightedBackgroundColor;
                    _nonHighlightedBackgroundColor = nonHighlightedBackgroundColor;
                    self.backgroundColor = nonHighlightedBackgroundColor;
                }
                return self;
            }
        
        
            -(void)setHighlighted:(BOOL)highlighted
            {
                if(highlighted)
                {
                    self.backgroundColor = self.highlightedBackgroundColor;
                }
                else
                {
                    self.backgroundColor = self.nonHighlightedBackgroundColor;
                }
            }
        

        然后,当我分配此单元格时,我指定突出显示和未突出显示的背景颜色。

        这非常有效 - 当我选择单元格时,颜色就是我想要的。

        【讨论】:

          猜你喜欢
          • 2013-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多