UIEditMenuInteraction是iOS16中新增的菜单交互类,用于取代UIMenuController
与 UIMenuItem
。目前 UITextField
与 UITextView
已经默认支持UIEditMenuInteraction
- 下面的代码主要是在UITextField中的使用
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
lazy var textField: UITextField = {
let _textField = UITextField(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40.0, height: 44.0))
_textField.borderStyle = .roundedRect
_textField.delegate = self
_textField.center = self.view.center
_textField.text = "UIEditMenuInteraction"
return _textField
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.textField)
}
// MARK: 通过代理方法添加交互的菜单
func textField(_ textField: UITextField, editMenuForCharactersIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
let _copy = UIAction(title: "复制") { _ in
print("复制内容")
}
let _favorite = UIAction(title: "喜欢") { _ in
print("喜欢收藏")
}
let _share = UIAction(title: "分享") { _ in
print("分享")
}
let _delete = UIAction(title: "删除", attributes: [.keepsMenuPresented]) { _ in
print("删除")
}
let _menu = UIMenu(title: "测试", preferredElementSize: .small, children: [_copy,_favorite,_share,_delete])
return _menu
}
}
网友评论