Last active
May 23, 2017 03:39
-
-
Save wanbok/8ef8b46b9d49d39b706c to your computer and use it in GitHub Desktop.
Copyable UILabel
This file contains hidden or 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
// | |
// CopyableLabel.swift | |
// | |
// Created by Wanbok Choi on 2016. 3. 17.. | |
// | |
import UIKit | |
final class CopyableLabel: UILabel { | |
override var canBecomeFirstResponder: Bool { return true } | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
self.isUserInteractionEnabled = true | |
self.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPressGesture(recognizer:)))) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { | |
return action == #selector(self.copy(_:)) | |
} | |
func handleLongPressGesture(recognizer: UIGestureRecognizer) { | |
becomeFirstResponder() | |
let menu = UIMenuController.shared | |
if !menu.isMenuVisible { | |
menu.setTargetRect(bounds, in: self) | |
menu.setMenuVisible(true, animated: true) | |
} | |
} | |
// MARK: - UIResponderStandardEditActions | |
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