UILabel-UIMenuController菜单项的长按手势 [英] UILabel - Long press gesture for menu item of UIMenuController
问题描述
我需要在整个应用中对UILable进行长按操作/手势,并且它应该显示这样的菜单,并带有自定义菜单选项:
I need to handle long press action/gesture on UILable, in an entire app, and it should show a menu like this, with custom menu options:
根据apple界面指南,文本字段,文本视图,Web视图和图像视图只能启用此菜单.
As per apple interface guideline a text field, a text view, a web view, and an image view can only enable this menu.
在UILabel中为整个应用添加此类操作并通过添加现有菜单选项来打开自定义菜单是否可行?
Is it feasible to add such action in UILabel for the entire app and open custom menu by adding own menu options, with existing?
推荐答案
这里是一个UILabel
子类,该子类可以处理长按以显示UIMenuController
的情况.您还可以在用例的菜单控制器中添加更多操作.
Here is a UILabel
subclass that handles long pressing to show the UIMenuController
. You can also add more actions the the menu controller for use case.
import UIKit
class MenuLabel: UILabel {
override var canBecomeFirstResponder: Bool {
return true
}
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isUserInteractionEnabled = true
addGestureRecognizer(
UILongPressGestureRecognizer(
target: self,
action: #selector(handleLongPressed(_:))
)
)
}
// MARK: - Actions
internal func handleLongPressed(_ gesture: UILongPressGestureRecognizer) {
guard let gestureView = gesture.view, let superView = gestureView.superview else {
return
}
let menuController = UIMenuController.shared
guard !menuController.isMenuVisible, gestureView.canBecomeFirstResponder else {
return
}
gestureView.becomeFirstResponder()
menuController.menuItems = [
UIMenuItem(
title: "Custom Item",
action: #selector(handleCustomAction(_:))
),
UIMenuItem(
title: "Copy",
action: #selector(handleCopyAction(_:))
)
]
menuController.setTargetRect(gestureView.frame, in: superView)
menuController.setMenuVisible(true, animated: true)
}
internal func handleCustomAction(_ controller: UIMenuController) {
print("Custom action!")
}
internal func handleCopyAction(_ controller: UIMenuController) {
UIPasteboard.general.string = text ?? ""
}
}
要从中获得的主要好处是:
Key things to takeaway from this are:
- 确保标签覆盖
canBecomeFirstResponder
-
isUserInteractionEnabled
设置为true - 在长按处理程序中呼叫
gestureView.becomeFirstResponder()
- making sure the label overrides
canBecomeFirstResponder
isUserInteractionEnabled
set to true- calling
gestureView.becomeFirstResponder()
in the long press handler
您可以将此标签添加到Interface Builder或用代码创建.
You can add this label to Interface Builder or create it in code.
希望这会有所帮助!
这篇关于UILabel-UIMenuController菜单项的长按手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!