LoginSignup
0
0

More than 5 years have passed since last update.

長押しでコピー可能なUIButton

Posted at

毎回作るのが嫌なので、クラスを貼っておく。
これをコピペして、nibのボタンのクラスをUIButtonからUIButtonWithCopyMenuに変更すると長押しでCopyメニューが表示されます。

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
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0