Swift开发实现编辑内容@部分高亮(类似发微博)

前几天项目有一个类似发微博时@用户的需求,网上也没找到比较好的第三方,自己DIY了一个,希望可以帮到有需要的朋友!

看看代码

  • 给UITextView写一个继承子类
class ZQMentionTextView: UITextView,UITextViewDelegate {

    /**提示文字*/
    var placeholderText:String?
    
    /**提示颜色*/
    var placeholderColor:UIColor?
   
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        delegate = self
    }
    

    /// 视图加载完设置提示文字及颜色
    override func draw(_ rect: CGRect) {
        text = placeholderText ?? ""
        textColor = placeholderColor ?? .black
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// UITextViewDelegate - 文本发生改变
    func textViewDidChange(_ textView: UITextView) {

        let selectedRange = textView.markedTextRange
        /// 有联想词时取消遍历查找
        guard let start =  selectedRange?.start else {
            findAllKeywordsChangeColor(textView: textView)
            return
        }
        /// 有联想词时取消遍历查找
        if textView.position(from: start, offset: 0) != nil {
            return
        }
    }

    /// 动态修改@和空格中间的字体颜色(本扩展的核心代码)
    ///
    /// - 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)!))
        // 正则匹配到@和空格之间的内容
        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)
        // 光标还原
        textView.selectedRange = rangeNow
    }
}

  • 调用
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 = "加个话题,更能被注意哦"
        textView.placeholderColor = .lightGray
        textView.font = UIFont.systemFont(ofSize: 15)
        view.addSubview(textView)
    }
}



- 效果图
效果图
  • 源码地址
    https://github.com/zhengqichen/ZQMentionTextView

你可能感兴趣的:(Swift开发实现编辑内容@部分高亮(类似发微博))