使用 Hamza Ansari 的答案并为 Swift 4.2 制作了它:
extension UITextView {
func setBulletList(text:String, bullet: String, bulletColor: UIColor, attributes: [NSAttributedString.Key: Any]) {
let r0 = text.replacingOccurrences(of: ",", with: "\n" + bullet)
let r = bullet + r0
let attributedString = NSMutableAttributedString(string: r)
attributedString.addAttributes(attributes, range: NSMakeRange(0, attributedString.length))
let greenColorAttribure = [NSAttributedString.Key.foregroundColor: bulletColor]
do {
let regex = try NSRegularExpression(pattern: bullet, options: NSRegularExpression.Options.caseInsensitive)
regex.enumerateMatches(in: r as String, options: [], range: NSMakeRange(0, r.count), using: { (result, flags, pointer) -> Void in
if let result = result{
attributedString.addAttributes(greenColorAttribure, range:result.range)
}
})
self.attributedText = attributedString
} catch {
self.attributedText = attributedString
}
}
}
用法:
lazy var textView: UITextView = {
let view = UITextViewFixed()
view.setBulletList(text: "Tags,Users,Jobs", bullet: "● ", bulletColor: UIColor.red, attributes: [
NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)
])
return view
}()