-
-
Save alfian0/c21a3e8ae591bd7bd3e2cdd658c6d4e1 to your computer and use it in GitHub Desktop.
Copyable UILabel
This file contains 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
// | |
// SRCopyableLabel.swift | |
// | |
// Created by Stephen Radford on 08/09/2015. | |
// Copyright (c) 2015 Cocoon Development Ltd. All rights reserved. | |
// | |
import UIKit | |
class SRCopyableLabel: UILabel { | |
override public var canBecomeFirstResponder: Bool { | |
get { | |
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(sender:)) | |
)) | |
} | |
override func copy(_ sender: Any?) { | |
UIPasteboard.general.string = text | |
UIMenuController.shared.setMenuVisible(false, animated: true) | |
} | |
func showMenu(sender: Any?) { | |
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(copy(_:)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment