-
-
Save renesugar/da97584e0bef868f177153ebb57aa47d to your computer and use it in GitHub Desktop.
Make UILabel Copyable in Swift 3. Special thanks to Stephen Radford and his "Make UILabel Copyable in Swift" article http://stephenradford.me/make-uilabel-copyable/
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 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 init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
sharedInit() | |
} | |
func sharedInit() { | |
isUserInteractionEnabled = true | |
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu))) | |
} | |
func showMenu(sender: AnyObject?) { | |
becomeFirstResponder() | |
let menu = UIMenuController.shared | |
if !menu.isMenuVisible { | |
menu.setTargetRect(bounds, in: self) | |
menu.setMenuVisible(true, animated: true) | |
} | |
} | |
override func copy(_ sender: Any?) { | |
let board = UIPasteboard.general | |
board.string = text | |
let menu = UIMenuController.shared | |
menu.setMenuVisible(false, 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