Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import UIKIt
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
_commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
_commonInit()
}
private func _commonInit() {
isUserInteractionEnabled = true
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(didPressedLong(_:)))
addGestureRecognizer(recognizer)
}
@objc
private func didPressedLong(_ recognizer: UILongPressGestureRecognizer) {
guard recognizer.state == .recognized else {
return
}
let menuController = UIMenuController.shared
guard !menuController.isMenuVisible else {
return
}
if #available(iOS 13.0, *) {
menuController.showMenu(from: self, rect: bounds)
} else {
menuController.setTargetRect(bounds, in: self)
menuController.setMenuVisible(true, animated: true)
}
}
override var canBecomeFirstResponder: Bool {
true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if [#selector(UIResponderStandardEditActions.copy)].contains(action) {
return true
}
// next responderに流す
return super.canPerformAction(action, withSender: sender)
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment