我需要将带有分隔符的字符串转换为属性字符串。 我的分隔符是$$斜体$$和$$$大胆$$$。实际上,只有当我没有使用斜体和粗体时,我的代码才是函数。我的麻烦是$$$$$大胆和斜体$$$$$。只设置了斜体...
这是我在UIViewcontroller类中的代码:
func pikipiki2AttributedString(text: String) -> NSAttributedString {
let attributedText = NSMutableAttributedString(string: text)
let size = [NSFontAttributeName : UIFont.systemFontOfSize(15.0)]
attributedText.addAttributes(size, range: NSRange(location: 0, length: attributedText.length))
let attributeBold = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15)]
try! attributedText.addAttributes(attributeBold, delimiter: "$$$")
let attributeItalic = [NSFontAttributeName: UIFont.italicSystemFontOfSize(15)]
try! attributedText.addAttributes(attributeItalic, delimiter: "$$")
return attributedText
}
创建了here的扩展程序:
public extension NSMutableAttributedString {
func addAttributes(attrs: [String : AnyObject], delimiter: String) throws {
let escaped = NSRegularExpression.escapedPatternForString(delimiter)
let regex = try NSRegularExpression(pattern:"\(escaped)(.*?)\(escaped)", options: [])
var offset = 0
regex.enumerateMatchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count)) { (result, flags, stop) -> Void in
guard let result = result else {
return
}
let range = NSRange(location: result.range.location + offset, length: result.range.length)enter code here
self.addAttributes(attrs, range: range)
let replacement = regex.replacementStringForResult(result, inString: self.string, offset: offset, template: "$1")
self.replaceCharactersInRange(range, withString: replacement)
offset -= (2 * delimiter.characters.count)
}
}
}