首页 > 解决方案 > 在 Swift/Objective-C 中重用 tableviewcell 时,属性标签不会消失

问题描述

对于表格视图,我从来没有遇到过重复使用单元格后文本标签持续存在的问题。

当您在数据源更改后重新加载 tableview 时,tableviewcells 会获取最新数据并相应地绘制自己。

但是,我现在遇到了属性标签的问题。从数据源中删除项目以便重新使用 tableviewcell 后,属性标签会保留在单元格中。不用说,剩余的属性标签与单元格中的内容无关。它只是附着在细胞上,不会消失。

问题描述如下:

在上面的答案中,该人说他在对常规文本标签进行任何操作之前将其设置为 nil,从而摆脱了属性标签。

transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
Or, if I reset the attributedText first, and then reset the text, it also works:

transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
transactionDescriptionLabel.text = nil
transactionValueLabel.text = nil 

将属性标签设置为 nil 似乎可以解决我的问题,但我以前从未将常规 textLabel 设置为 nil,并且我试图了解为什么我必须将属性标签设置为 nil。

当你有一个属性标签时,当你出列单元格时是否需要将它设置为 nil ?或者,除了将其设置为空字符串之外,当您不再在 tableview 中显示它时,让它消失的正确方法是什么?

在此先感谢您的任何建议。

标签: iosobjective-cswift

解决方案


我只是偶然发现了与NSUnderlineStyleAttributeName. 仅当满足条件时,我才必须在 a 中的某些文本下划线UILabelUITableViewCell滚动单元格后,标签会继续重用属性。

我尝试了几种解决方法,通过设置label.textlabel.attributedTextto nil,删除属性等......没有任何效果。

最后,我找到了查看NSAttributedString文档的实际解决方案(RTFM,始终是答案):

为下划线和删除线属性定义了枚举:

NSUnderlineStyleNone = 0x00

UIKIT_EXTERN NSAttributedStringKey const NSStrikethroughStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0));  // NSNumber containing integer, default 0: no strikethrough
UIKIT_EXTERN NSAttributedStringKey const NSUnderlineStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0));      // NSNumber containing integer, default 0: no underline

总之,删除下划线或罢工属性的实际方法是将其设置为NSUnderlineStyleNoneor 0

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
[attributeString setAttributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleNone)} range:(NSRange){0, [attributeString length]}];
label.attributedText = attributeString;

推荐阅读