NSMutableAttributedString UILabel 在选中时不会保留其属性



我在保留属性 NSMutableString 时遇到问题。我有一个UITableView,每个UITableViewCell都有一个属性文本。设置属性文本没有问题,但在选择后,UITableViewCell 的属性会丢失。这是我在cellForRowAtIndexPath中的代码,用于设置属性:

  NSMutableAttributedString *changesStyleString_h = [[NSMutableAttributedString alloc] initWithString:@"Attributes change!" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:20], NSForegroundColorAttributeName:[UIColor yellowColor]}];
[changesStyleString_h addAttributes:@{ NSUnderlineStyleAttributeName:@(1)} range:NSMakeRange(11, 6)];
cell.mainLabel.attributedText = changesStyleString

我可以指出,mainLabel 也是一个 UILabel,那里没有自定义。任何正确方向的帮助将不胜感激!

我发现我需要在整个字符串上设置属性,否则它会做一些时髦的事情。

NSString* string = @"1 - some string"
NSMutableAttributedString* string = [[NSMutableAttributedString alloc] initWithString:string];
[string setAttributes:@{NSForegroundColorAttributeName: accent, NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:13.f]} range:NSMakeRange(0, 1)];

这会导致突出显示单元格时出现奇怪的行为。

但是,当我这样做时:

[string setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:NSMakeRange(1, [labelTwo length] - 1)];

一切似乎都按预期进行。

希望对您有所帮助!

最新更新