这是一个简单的问题,但在几个地方出错,所以我认为有些东西我没有得到(而且这是一个不再在这里的同事应用程序)。我正在将Objective-C应用程序迁移到Swift,并且在使用NSAttributedString时遇到了一些问题。
有一个note.body被设置为NSMutableAttributedString,每个音符都有一个.frags字符串数组,这是我们要添加属性的部分。
我有:
var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(9.0)]
var gString = NSMutableAttributedString(string:note.body, attributes:attrs) // say note.body="birds and bees"
let firstAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(), NSBackgroundColorAttributeName: UIColor.yellowColor(), NSUnderlineStyleAttributeName: 1]
for (val) in note.frags { // say note.frags=["bees"]
let tmpVal = val
gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: gString.string.rangeOfString(tmpVal))
}
我如何添加第一个属性?
我得到的错误是:
无法使用类型'的参数列表调用'addAttribute'(String, value:Int,range:Range?)'
答案 0 :(得分:3)
问题是,当您需要Range?
时,您使用NSRange
参数调用该方法。
要确保获得NSRange
,您需要先将String
转换为NSString
。
此代码适用于Playground:
for val in note.frags { // say note.frags=["bees"]
let range: NSRange = NSString(string: gString.string).rangeOfString(val)
gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: range)
}