使 UiTextField 仅接受粘贴选项 - Swift

Make UiTextField accept only paste option - Swift

我想让 UiTextField 在长按时只接受粘贴选项,而不像 iOS phone 应用程序那样显示键盘和光标。

我尝试使用委托方法删除键盘,但现在确实出现了粘贴选项。

你能帮帮我吗?

@IBOutlet weak var phoneNumberTf:UITextField? {
didSet {
    phoneNumberTf?.backgroundColor = .clear
    phoneNumberTf?.textAlignment = .left
    phoneNumberTf?.font = UIFont().font_regular(ofSize: 38)
    phoneNumberTf?.delegate = self
    }
}
extension KeypadView: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return false
    }
}

您可以通过使用长按手势识别器子类化 UILabel 并设置 UIMenuController 来创建您的实现。

class MenuLabel: UILabel {

    override var canBecomeFirstResponder: Bool {
        return true
    }

    // MARK: - Init

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        isUserInteractionEnabled = true
        addGestureRecognizer(
            UILongPressGestureRecognizer(
                target: self,
                action: #selector(handleLongPressed(_:))
            )
        )
    }

    // MARK: - Actions

    @objc internal func handleLongPressed(_ gesture: UILongPressGestureRecognizer) {
        guard let gestureView = gesture.view, let superView = gestureView.superview else {
            return
        }

        let menuController = UIMenuController.shared

        guard !menuController.isMenuVisible, gestureView.canBecomeFirstResponder else {
            return
        }

        gestureView.becomeFirstResponder()

        menuController.menuItems = [
            UIMenuItem(
                title: "Paste",
                action: #selector(handlePasteAction(_:))
            ),
        ]

        menuController.showMenu(from: superView, rect: gestureView.frame)
    }

    @objc internal func handlePasteAction(_ controller: UIMenuController) {
        self.text = UIPasteboard.general.string
    }
}

长按后,UIMenuController 将显示一个粘贴选项,然后将 UILabel 的文本值设置为 UIPasteboard.general.string