ios - NSAttributedstring 不能快速工作

标签 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
}

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

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

最佳答案

罪魁祸首是Range。使用 NSRange 而不是范围。这里需要注意的另一件事是,简单地将 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
}

关于ios - NSAttributedstring 不能快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30594167/

相关文章:

ios - 我的 UIPageViewController 不断崩溃

ios - 计算 UILabel 中可见文本的范围

objective-c - 在 NSTextView 上设置范围长度为零的属性?

linux - 关闭终端后无法在 Ubuntu 下运行 Swift

ios - 如何使用 Firestore 数据库快速设置 TableView 中项目列表的后缀?

ios - 在 swift 2.0 中一次显示一个字符的文本

iOS9 Xcode 7 - 核心数据 - 避免重复对象

ios - UIImage 比它的 NSData 占用更多的内存

ios - UITableView header 中容器 View 的高度错误

swift - UIPickerView 选择输入 Swift 4 或 5