为什么NSMutableAttributedString在某些情况下会忽略背景颜色属性?

问题描述 投票:1回答:2

我遇到了一个令人沮丧的问题。我希望标签显示文本字符串,并且该字符串的部分具有不同的背景颜色。

此代码有效:

let s = NSMutableAttributedString(string: "test me bar", attributes: [:])
s.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(),
   range: NSMakeRange(4, 2))
s.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blueColor(), 
   range: NSMakeRange(8, 2))

self.detailDescriptionLabel.attributedText = s

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS94dzJHWi5wbmcifQ==” alt =“在此处输入图像描述”>

但是如果我准确地删除对addAttribute的那些调用之一(无关紧要),以便我恰好将字符串的一个范围指定为具有背景颜色属性,则在背景中的任何位置都不会显示背景颜色字符串。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PeWhCUi5wbmcifQ==” alt =“在此处输入图像描述”>

我使用的是iOS 8.1,这发生在模拟器和iPhone 6中。我在代码中发现了此问题,并仅在一个空项目中使用上述代码片段重现了此问题。

有什么想法吗?我在这里拔头发。这是问题的精简版本,但是对于我的项目而言,重要的是要能够具有仅一个区域具有背景颜色的字符串。

EDIT如果我将背景色之一设置为UIColor.clearColor(),则所有颜色均按预期方式工作。我也许正在查看UIKit中的错误?

ios background-color nsattributedstring nsmutableattributedstring
2个回答
2
投票

您首先需要在整个文本中应用透明颜色的NSBackgroundColorAttributeName

[s addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:(NSRange){0, s.length}];

然后,您可以将第二种颜色与要突出显示的文本范围一起应用。

[s addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:(NSRange){0, 2}];

对于Swift

mutableAttributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear , range: {0, 2})

mutableAttributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow , range: {0, 2})

0
投票

这也是您的错误:

只需这样做:

self.detailDescriptionLabel.numberOfLines = 2; // <---

您的问题已解决。

© www.soinside.com 2019 - 2024. All rights reserved.