Skip to content

Instantly share code, notes, and snippets.

@cscouto
Created March 16, 2018 19:32
Show Gist options
  • Save cscouto/28f20f1ef7099e68009baf7410712c39 to your computer and use it in GitHub Desktop.
Save cscouto/28f20f1ef7099e68009baf7410712c39 to your computer and use it in GitHub Desktop.
SWIFT - Copying with UIMenuController from a UILabel
import UIKit
class InterctiveLabel: UILabel {
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
self.backgroundColor = UIColor(hex: "EEEEEE")
return (action == #selector(UIResponderStandardEditActions.copy(_:)))
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
self.backgroundColor = UIColor.white
}
}
import UIKit
class MessageCell: UITableViewCell {
@IBOutlet weak var labelMessage: UILabel!
override func layoutSubviews() {
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture))
labelMessage.addGestureRecognizer(gestureRecognizer)
}
func handleLongPressGesture(recognizer: UIGestureRecognizer) {
guard recognizer.state == .recognized else { return }
if let recognizerView = recognizer.view,
let recognizerSuperView = recognizerView.superview,
recognizerView.becomeFirstResponder()
{
let menuController = UIMenuController.shared
menuController.setTargetRect(recognizerView.frame, in: recognizerSuperView)
menuController.setMenuVisible(true, animated:true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment