前幾天項(xiàng)目有一個(gè)類似發(fā)微博時(shí)@用戶的需求,網(wǎng)上也沒找到比較好的第三方垄琐,自己DIY了一個(gè)边酒,希望可以幫到有需要的朋友!
看看代碼
- 給UITextView寫一個(gè)繼承子類
class ZQMentionTextView: UITextView,UITextViewDelegate {
/**提示文字*/
var placeholderText:String?
/**提示顏色*/
var placeholderColor:UIColor?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
delegate = self
}
/// 視圖加載完設(shè)置提示文字及顏色
override func draw(_ rect: CGRect) {
text = placeholderText ?? ""
textColor = placeholderColor ?? .black
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// UITextViewDelegate - 文本發(fā)生改變
func textViewDidChange(_ textView: UITextView) {
let selectedRange = textView.markedTextRange
/// 有聯(lián)想詞時(shí)取消遍歷查找
guard let start = selectedRange?.start else {
findAllKeywordsChangeColor(textView: textView)
return
}
/// 有聯(lián)想詞時(shí)取消遍歷查找
if textView.position(from: start, offset: 0) != nil {
return
}
}
/// 動(dòng)態(tài)修改@和空格中間的字體顏色(本擴(kuò)展的核心代碼)
///
/// - Parameter textView: textView
func findAllKeywordsChangeColor(textView:UITextView) {
let string = textView.text
let rangeDefault = textView.selectedRange
let attributedString = NSMutableAttributedString(string: string!)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: NSRange(location: 0, length: (string?.count)!))
// 正則匹配到@和空格之間的內(nèi)容
let reg = try? NSRegularExpression(pattern: "@[^\\s]+", options: [])
guard let matches = reg?.matches(in: string!, options: [], range: NSRange(location: 0, length: (string?.count)!)) else {
return
}
for result in matches {
let range = result.range(at: 0)
let subStr = (attributedString.string as NSString).substring(with: range)
let length = subStr.count
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSRange(location: range.location, length: length))
}
attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: (string?.count)!))
textView.attributedText = attributedString
let rangeNow = NSRange(location: rangeDefault.location, length: 0)
// 光標(biāo)還原
textView.selectedRange = rangeNow
}
}
- 調(diào)用
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 15, y:100, width: view.frame.width-30, height: view.frame.height-150)
let textView = ZQMentionTextView(frame: frame)
textView.placeholderText = "加個(gè)話題狸窘,更能被注意哦"
textView.placeholderColor = .lightGray
textView.font = UIFont.systemFont(ofSize: 15)
view.addSubview(textView)
}
}
- 效果圖