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 = "這是測試數(shù)據(jù),這段話要高亮"
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
}
}
測試效果