こんな感じで作れた。
swift
import UIKit
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
self.copyableInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// IB上の設定を引き継ぎたい場合はコメントアウト
self.copyableInit()
}
func copyableInit() {
self.userInteractionEnabled = true
self.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(CopyLabel.showContextMenu(_:))))
}
func showContextMenu(sender:AnyObject?) {
self.becomeFirstResponder()
let contextMenu = UIMenuController.sharedMenuController()
if !contextMenu.menuVisible {
contextMenu.setTargetRect(self.bounds, inView: self)
contextMenu.setMenuVisible(true, animated: true)
}
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func copy(sender: AnyObject?) {
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = text
let contextMenu = UIMenuController.sharedMenuController()
contextMenu.setMenuVisible(false, animated: true)
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy(_:)) {
return true
}
return false
}
}