Created
December 19, 2017 09:33
-
-
Save Marcocanc/1e25cd2aebc30e8e9022030b9ebbe9c2 to your computer and use it in GitHub Desktop.
UILabel subclass that supports Copying its contents to clipboard
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
import UIKit | |
class UILabelCopyable: UILabel { | |
override func copy(_ sender: Any?) { | |
UIPasteboard.general.string = text | |
} | |
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { | |
return action == #selector(copy(_:)) && text != nil | |
} | |
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { | |
becomeFirstResponder() | |
let menuController = UIMenuController.shared | |
if !menuController.isMenuVisible { | |
menuController.setTargetRect(menuTargetRect, in: self) | |
menuController.setMenuVisible(true, animated: true) | |
} | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
commonInit() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
commonInit() | |
} | |
func commonInit() { | |
isUserInteractionEnabled = true | |
} | |
override var canBecomeFirstResponder: Bool { return true } | |
var menuTargetRect: CGRect { | |
let intrinsicRect = CGRect(origin: .zero, size: intrinsicContentSize) | |
return bounds.intersection(intrinsicRect) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment