Created
November 19, 2020 06:35
-
-
Save ha1f/9515578586cc1f077a965e07a8bc8587 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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