-
-
Save zyrx/67fa2f42b567d1d4c8fef434c7987387 to your computer and use it in GitHub Desktop.
// | |
// 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) | |
} | |
} |
Thank you so much Stephen Radford
Thanks but. how can i show toast after being copied?
I get a compile erro
Please help
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action #selector(showMenu)))
Cannot invoke initializer for type 'UILongPressGestureRecognizer' with an argument list of type '(target: calculatorLabel, (CALayer, String) -> CAAction?, Selector)
Argument of '#selector' refers to instance method 'showMenu(sender:)' that is not exposed to Obejective-C
Add '@objc' to expose this instance method to Objective-C
Expected ',' separator
Just click "Fix" button in the error dialog.
but how i can select on UILabel?
but how i can select on UILabel?
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
I think that "text" is supposed to be where your UILabel's text goes.
I can find this code example in a 1000 places, but all it does is copying the entire label. No selection possible, so kinda useless. Or am I missing something ?
I get a compile erro
Please help
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action #selector(showMenu)))
Cannot invoke initializer for type 'UILongPressGestureRecognizer' with an argument list of type '(target: calculatorLabel, (CALayer, String) -> CAAction?, Selector)
Argument of '#selector' refers to instance method 'showMenu(sender:)' that is not exposed to Obejective-C
Add '@objc' to expose this instance method to Objective-C
Expected ',' separator