问题
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
.
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:
回答1:
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(_:)))
}
}
You can then simple drag drop the Label in Storyboard and make it of the type KGCopyableLabel and it should work
来源:https://stackoverflow.com/questions/45541208/i-want-native-ios-copy-and-paste-ui-on-uilabel