Skip to content

Instantly share code, notes, and snippets.

@syou007
Created June 7, 2017 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syou007/6381cb5d0e6be98476a6109013198072 to your computer and use it in GitHub Desktop.
Save syou007/6381cb5d0e6be98476a6109013198072 to your computer and use it in GitHub Desktop.
長押しでコピー可能なUIButton ref: http://qiita.com/syou007/items/d0d97e5d9d70a85f33db
import UIKit
// コピーメニューが表示されるUIButton
class UIButtonWithCopyMenu: UIButton {
override func awakeFromNib() {
// 長押し処理を追加
self.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(UIButtonWithCopyMenu.showContextMenu(_:))))
}
// コンテンツをコピーできるようにします。
func showContextMenu(_ sender:AnyObject?) {
self.becomeFirstResponder()
let contextMenu = UIMenuController.shared
if !contextMenu.isMenuVisible {
contextMenu.setTargetRect(self.bounds, in: self)
contextMenu.setMenuVisible(true, animated: true)
}
}
// コンテンツをコピーします。
override func copy(_ sender: Any?) {
let pasteBoard = UIPasteboard.general
pasteBoard.string = self.titleLabel?.text
let contextMenu = UIMenuController.shared
contextMenu.setMenuVisible(false, animated: true)
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(copy(_:)) {
return true
}
return false
}
override var canBecomeFirstResponder: Bool {
get {
return true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment