Skip to content

Instantly share code, notes, and snippets.

@wanbok
Last active May 23, 2017 03:39
Show Gist options
  • Save wanbok/8ef8b46b9d49d39b706c to your computer and use it in GitHub Desktop.
Save wanbok/8ef8b46b9d49d39b706c to your computer and use it in GitHub Desktop.
Copyable UILabel
//
// 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