我在iOS Label对象中有一个URL地址列表。用户似乎无法从列表中选择和复制项目并将其粘贴到iOS设备上的Safari浏览器中。有没有办法实现这个目标?
答案 0 :(得分:5)
UILabel
中没有此功能。
您需要使用UITextField
或UITextView
。另外不要忘记改变它的外观并使用
[... setEditable:NO];
答案 1 :(得分:5)
实际上可以使用UILabel,只需要进行一些子类化。
最终结果: 当用户长按标签时,他或她会看到一个复制气球。
以下是允许制作标签可复制的步骤(我记得):
斯威夫特3:
let menu = UIMenuController.shared
if !menu.isMenuVisible {
self.becomeFirstResponder()
menu.setTargetRect(self.bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
斯威夫特3:
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.copy(_:))
}
斯威夫特3:
let menu = UIMenuController.shared
let labelText = self.text ?? self.attributedText?.string
if let uLabelText = labelText {
let clipBoard = UIPasteboard.general
clipBoard.string = uText
}
menu.setMenuVisible(false, animated: true)
答案 2 :(得分:0)
这是JoriDor解决方案的快速5版本;
class CopyableLabel: UILabel {
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:))))
}
@objc
func showMenu(sender: AnyObject?) {
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy(_:)) {
return true
}
return false
}
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
}