Created
June 7, 2017 07:05
-
-
Save syou007/6381cb5d0e6be98476a6109013198072 to your computer and use it in GitHub Desktop.
長押しでコピー可能なUIButton ref: http://qiita.com/syou007/items/d0d97e5d9d70a85f33db
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 | |
// コピーメニューが表示される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