Last active
March 11, 2020 14:21
-
-
Save zyrx/67fa2f42b567d1d4c8fef434c7987387 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 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) | |
} | |
} |
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 ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
but how i can select on UILabel?