【问题标题】:NSAttributed string not working in swiftNSAttributedstring 不能快速工作
【发布时间】:2015-06-02 20:19:56
【问题描述】:

我正在尝试使用属性字符串来自定义标签,但在 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
}

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

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

【问题讨论】:

标签: ios swift nsattributedstring


【解决方案1】:

罪魁祸首是范围。使用 NSRange 而不是 Range。这里要注意的另一件事是,简单地将 self.text 转换为 NSString 会给您强制展开错误。

因此,请改用“self.text! as NSString”。

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】:

    你的问题是你传递了一个 swift 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)
    

    【讨论】:

      【解决方案3】:

      尝试使用 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
      }
      

      【讨论】:

        猜你喜欢
        • 2016-03-21
        • 2014-10-22
        • 2021-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多