我想要本机iOS在UILabel上复制并粘贴UI [英] I want native iOS copy and paste UI on UILabel
问题描述
我想创建iOS提供的本机复制和粘贴体验,当您点击并按住UITextField
时-我希望它在UILabel
而不是UITextField
上运行.
I want to create the native Copy and Paste experience that iOS provides when you tap and hold a UITextField
- but I want it to work on a UILabel
instead of a UITextField
.
这是可能的,还是仅适用于UITextField
的东西?
我是否需要创建自己的自定义UI并在UIPasteboard
中搞乱,还是有一个更雄辩的解决方案?
Is this possible, or is it something that only works with UITextField
?
Would I need to create my own custom UI and mess around in UIPasteboard
or is there a more eloquent solution?
这是一个典型示例,尽管它通常还会显示放大的圆圈:
Here is a typical example, although it normally also shows the zoomed in circle:
推荐答案
很难在标签上执行标准的复制菜单.或者也许那时我尝试了但没有成功.因此,我刚刚实施了完整的复印解决方案.我做了下面的事情-
It is difficult to do the standard copy menu on the label. Or maybe at that time I tried but didnt succeed. So I just implemented a complete copy solution. I did it something like below -
import UIKit
class KGCopyableLabel: UILabel {
override public var canBecomeFirstResponder: Bool {
get {
return true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(
target: self,
action: #selector(showCopyMenu(sender:))
))
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
UIMenuController.shared.setMenuVisible(false, animated: true)
}
func showCopyMenu(sender: Any?) {
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return (action == #selector(copy(_:)))
}
}
然后,您可以简单地将Label拖放到Storyboard中,并将其设置为 KGCopyableLabel 类型,它应该可以工作
You can then simple drag drop the Label in Storyboard and make it of the type KGCopyableLabel and it should work
这篇关于我想要本机iOS在UILabel上复制并粘贴UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!