iOS textView 选中的字符串 高亮显示 2022-04-19


import UIKit
import PDFKit
import CoreGraphics

class ViewController: UIViewController, UITextViewDelegate {
    var dic:[String:[String:String]]?
    var textView = nowTextView()
    override func viewDidLoad() {
        super.viewDidLoad()
      
        
        let textview = nowTextView()
        textview.frame = CGRect.init(x: 0, y: 300, width: 200, height: 100);
        self.view.addSubview(textview)
        textview.textColor = .black
        textview.delegate = self
        //textview.isEditable = false
      //  textview.tintColor = .clear

        let menuController = UIMenuController.shared
        let item1 = UIMenuItem(title: "高亮显示", action: #selector(ViewController.test))
        let item2 = UIMenuItem(title: "测试2", action: #selector(ViewController.test))
        menuController.menuItems = [item1, item2]
        textview.text = "这是测试数据,这段话要高亮"
        self.textView = textview
         
    }
   @objc func test() {
       if let text = textView.text {
          if let textRange = textView.selectedRange {
            let attributedString = NSMutableAttributedString(string:text)
                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.red , range: textRange)
               self.textView.attributedText = attributedString
              }
          }

    }

}
extension UITextInput {
    var selectedRange: NSRange? {
        guard let range = self.selectedTextRange else { return nil }
        let locatione = self.offset(from: self.beginningOfDocument, to: range.start)
        let length = self.offset(from:range.start, to: range.end)
        return NSRange(location: locatione, length: length)
    }
}
class nowTextView:UITextView ,UITextViewDelegate{
    open override func canPerformAction(_ action: Selector, withSender
        sender: Any?) -> Bool {
        print(action)
        if action == #selector(cut(_:)) {
            return true
        }
        return false
    }
    
}


测试效果


image.png

你可能感兴趣的:(iOS textView 选中的字符串 高亮显示 2022-04-19)