可选择的UILabel内容

时间:2013-03-03 18:07:32

标签: ios uilabel

我在iOS Label对象中有一个URL地址列表。用户似乎无法从列表中选择和复制项目并将其粘贴到iOS设备上的Safari浏览器中。有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:5)

UILabel中没有此功能。

您需要使用UITextFieldUITextView。另外不要忘记改变它的外观并使用

[... setEditable:NO];

答案 1 :(得分:5)

实际上可以使用UILabel,只需要进行一些子类化。

最终结果: 当用户长按标签时,他或她会看到一个复制气球。

Picture showing copy-balloon after long-pressing a label on iOS

以下是允许制作标签可复制的步骤(我记得):

  1. 子类UILabel
  2. 设置userInteractionEnabled = YES
  3. 覆盖canBecomeFirstResponder并返回true
  4. 添加UILongPressGestureRecognizer
  5. 成为第一响应者&目前UIMenuController
  6. 斯威夫特3:

    let menu = UIMenuController.shared
    if !menu.isMenuVisible {
        self.becomeFirstResponder()
        menu.setTargetRect(self.bounds, in: self)
        menu.setMenuVisible(true, animated: true)
    }
    
    1. 覆盖canPerformAction以允许复制
    2. 斯威夫特3:

      override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
              return action == #selector(UIResponderStandardEditActions.copy(_:))
      }
      
      1. 覆盖复制方法,UIPasteboard文本&隐藏UIMenuController
      2. 斯威夫特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)
    }
    
}