Skip to content

Instantly share code, notes, and snippets.

@nerdo
Forked from zyrx/CopyableLabel.swift
Last active February 11, 2018 17:28
Show Gist options
  • Save nerdo/17f7262744106455a771a3c5e8e05f0b to your computer and use it in GitHub Desktop.
Save nerdo/17f7262744106455a771a3c5e8e05f0b to your computer and use it in GitHub Desktop.
Make UILabel Copyable in Swift 4. Special thanks to Stephen Radford and his "Make UILabel Copyable in Swift" article http://stephenradford.me/make-uilabel-copyable/
//
// CopyableLabel.swift
//
// Created by Lech H. Conde on 01/11/16.
// Copyright © 2016 Mavels Software & Consulting. All rights reserved.
//
import UIKit
class CopyableLabel: UILabel {
override var canBecomeFirstResponder: Bool {
return true
}
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu)))
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
UIMenuController.shared.setMenuVisible(false, animated: true)
}
@objc func showMenu(sender: AnyObject?) {
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.copy)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment