NSMutableAttributedString 未正确呈现

Posted

技术标签:

【中文标题】NSMutableAttributedString 未正确呈现【英文标题】:NSMutableAttributedString not rendering correctly 【发布时间】:2019-08-17 15:59:14 【问题描述】:

我正在使用 SplitViewController;主人是 tableView,有一系列 RightDetail 单元格,其属性字符串是通过值设置弹出框的回调设置的。

通过设置单元格的detailTextLabel 的方法传回和设置的值。它在DispatchQueue.main.async 中执行此操作,因为对detailTextLabel 的一些更新是通过来自Network.Framework 的调用进行的

奇怪的是,当弹出框进行更改时,属性字符串的更改没有正确显示。在正确绘制之前,焦点必须更改到下一个表格单元格。

因此,只有当焦点变为“流速”时,温度才能正确渲染,如图所示。

我已逐步执行以下代码并检查是否将正确的值写入self.buttonCell?.detailTextLabel?.attributedText

您还会看到我添加了setNeedsLayout()setNeedsFocusUpdate()

func setDetailValueWithUnit( to index: Int) 
    /** sets the detailtext to the value as the specified index and appends units.
        it does this within the main dispatchQueue as this method is called by
        operationResult which is called by the statemachine.
     **/
    DispatchQueue.main.async 
        let font = self.buttonCell?.detailTextLabel?.font
        let finalString = NSMutableAttributedString(string: valueString,attributes: [.font:font!])

        if let units = self.units() 
            finalString.append(units)
            self.buttonCell?.detailTextLabel?.attributedText = finalString

            //next 2 lines experimental in an attempt to fix the attributed text not
            //being consistently redendered correctly
            self.buttonCell?.detailTextLabel?.setNeedsLayout()
            self.buttonCell?.detailTextLabel?.setNeedsFocusUpdate()
            NSLog("setDetailValueWithUnit: %d", index)
            return
         else 
            assert(false, "No Units found")
        
    

【问题讨论】:

【参考方案1】:

问题是你所做的是完全错误的。你不应该直接触摸单元格的文本标签字体、文本或其他任何类似的东西。这不是表格视图的工作方式。您应该设置表格的数据模型并从那里更新表格,从而为可见单元格调用cellForRowAt:。这样,只有cellForRowAt: 配置单元格,一切都会好起来的。

【讨论】:

感谢您的回复。这是一个静态表,如果这有什么不同(可能不是)。抱歉,据我所知,我可能遗漏了一些东西,我没有更改我只是阅读它的字体,以便我可以在“finalString”上使用相同的字体,然后用于设置“attributedText”,猜猜没有区别!我最好对应用于静态表的模型进行一些研究。感谢您的指导。 "这是一个静态表" 我相信你自己的例子证明它不是。它与静态表相反。它的内容可以改变,所以它是一个动态表。我的答案没有任何变化。表不存储数据!它们反映数据。 它在故事板上是静态的,但数据不是! - 点了 - 谢谢。 我是说,知道数据会发生变化,您一开始就不应该在故事板中将其设为静态表。您需要一个数据模型对象,因此使该表“静态”是没有意义的。您可以将其保持为静态,但您仍然需要按照我说的做:更改 model 并重新加载数据,以便 cellForRowAt:被调用。 是的,我的代码需要重构并且您不会喜欢这样,但是您对单元格而不是其标签的关注在某种程度上促使我尝试了以下解决问题的方法:self.buttonCell?.setNeedsLayout( )。认为您刚刚为您的出版物找到了另一个客户。欣赏智慧。

以上是关于NSMutableAttributedString 未正确呈现的主要内容,如果未能解决你的问题,请参考以下文章

富文本(NSMutableAttributedString)

NSMutableAttributedString的使用

NSMutableAttributedString使用介绍

在 NSMutableAttributedString 上模拟“initWithAttributedString”的 OCMock 失败

NSMutableAttributedString-富文本的使用

NSMutableAttributedString 未正确呈现