NSAttributed字符串在swift中不起作用

时间:2015-06-02 10:59:53

标签: ios swift nsattributedstring

我正在尝试使用属性字符串来自定义标签,但在swift中会出现奇怪的错误。

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)
    var theRange: Range<String.Index>! = self.text?.rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text!)

    let attribute = [NSForegroundColorAttributeName as NSString: UIColor.blackColor()]
    attributedString.setAttributes(attribute, range: self.text?.rangeOfString(substring))
    self.attributedText = attributedString
}

我也尝试使用以下代码

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)
    var theRange: Range<String.Index>! = self.text?.rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text!)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: self.text?.rangeOfString(substring))
    self.attributedText = attributedString
}

在这两种情况下,得到奇怪的错误“无法使用类型'的参数列表调用'setAttributes'([NSString:...”

我已经尝试了大多数可用于堆栈溢出和其他许多教程的解决方案,但是,所有这些都导致了这样的错误。

3 个答案:

答案 0 :(得分:3)

您的问题是,您快速通过Range预计NSRange

从字符串中获取有效NSRange的解决方案是首先将其转换为NSString。请参阅NSAttributedString takes an NSRange while I'm using a Swift String that uses Range

所以这样的事情应该有效:

let nsText = self.text as NSString
let theRange = nsText.rangeOfString(substring)  // this is a NSRange, not Range

// ... snip ...

attributedString.setAttributes(attribute, range: theRange)

答案 1 :(得分:3)

主要罪魁祸首是Range。使用NSRange而不是Range。这里要注意的另一件事是,只需将self.text转换为NSString就会给出强制解包的错误。

因此,使用&#34; self.text!作为NSString&#34;代替。

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)!
    var range: NSRange = (self.text! as NSString).rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: range)
    self.attributedText = attributedString
}

答案 2 :(得分:0)

尝试使用NSRange而不是Range:

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)!
    var range: NSRange = (self.text as NSString).rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: range)
    self.attributedText = attributedString
}