从Label复制的菜单

时间:2017-08-14 12:45:32

标签: ios swift3

我有代码来复制Label中的数字。

我有一个复制按钮,我该怎么做才能点击它打开照片中的菜单然后点击复制按钮?

LoadKeyboardLayout does not change the UI of On screen keyboard

@IBAction func copybutton(_ sender: UIButton) {
    UIPasteboard.general.string = displayResultLabel.text
}

2 个答案:

答案 0 :(得分:1)

根据您的问题提供的信息量很少,希望我能正确理解问题。

我创建的示例的@minute包含UIViewControllerUILabel

每当按下该按钮时,屏幕将显示一个带有三个按钮的操作表单(UIButtonCopyPaste)。

当按下操作表中的View Memory按钮时,我们将复制标签的文本。

enter image description here

这是代码:

  

注意:

     

Copy名为UILabel

     

displayResultLabel的动作名为UIButton

showActionSheetButtonAction

答案 1 :(得分:0)

您需要UILabel的子类,并更改一些默认设置以实现此目的,首先您需要设置userInteractionEnable = true,默认情况下falseUILabel,您需要还会覆盖属性canBecomeFirstResponder,默认情况下也是false,之后您可以显示菜单成为标签firstResponder并使用UIMenuController和longPressGestureRecognizer,类完整代码在这里

使用此UILabel子类

import UIKit

class ContextMenuLabel: UILabel {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override func awakeFromNib() {
        super.awakeFromNib()
        self.isUserInteractionEnabled = true
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.showContextMenu))
        self.addGestureRecognizer(longPressGesture)
    }

    func showContextMenu()
    {
        self.becomeFirstResponder()
        UIMenuController.shared.setTargetRect(self.frame, in: self.superview!)
        let itemCopy = UIMenuItem(title: "Copy", action: #selector(self.copyAction))
        UIMenuController.shared.arrowDirection = .down
        UIMenuController.shared.menuItems = [itemCopy]
        UIMenuController.shared.setMenuVisible(true, animated: true)

        debugPrint(UIMenuController.shared.menuFrame)
    }

    func copyAction()
    {
        UIPasteboard.general.string = self.text
    }

    override var canBecomeFirstResponder: Bool{
        get{
            return true
        }
    }

}

<强>结果

enter image description here

希望这有帮助