簡體   English   中英

如果快速觸發按鈕上的長按手勢,如何獲取按鈕文本?

[英]How to get the button text if a long press gesture on the button is triggered in swift?

我定義了一個按鈕,並且在按鈕上添加了一個長按手勢識別器。 我知道可以通過定義如下函數來完成某些操作。 但是如何在檢測到手勢時獲取與按鈕關聯的標簽文本?

var removeBottomButton: UIButton = UIButton()
// set up the  button

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setRemoveButton()
        let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(clearBottom))
        self.removeBottomButton.addGestureRecognizer(longGesture)
        longGesture.minimumPressDuration = 1.5
    }

    func setRemoveButton() {
        removeBottomButton = UIButton(type: UIButton.ButtonType.system)
        removeBottomButton.translatesAutoresizingMaskIntoConstraints = false
        removeBottomButton.setTitle("Item Name AAA", for: .normal)
        removeBottomButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        removeBottomButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
        removeBottomButton.backgroundColor = UIColor.black
        removeBottomButton.layer.borderColor = UIColor.red.cgColor
        removeBottomButton.layer.cornerRadius = 10.0
        removeBottomButton.isUserInteractionEnabled = true
        view.addSubview(removeBottomButton)
        removeBottomButton.topAnchor.constraint(equalTo: view.bottomAnchor, constant: CGFloat(-50)).isActive = true
        removeBottomButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: CGFloat(20)).isActive = true
        removeBottomButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: CGFloat(-20)).isActive = true
        removeBottomButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: CGFloat(-20)).isActive = true
    }
//do something when the gesture is detected
    @objc func clearBottom(sender: UILongPressGestureRecognizer) {

        if sender.state == .ended {
            // how do I get the button text here? (i.e. "Item Name AAA")
        }

    }

@objc func clearBottom(sender: UILongPressGestureRecognizer) { 
    if sender.state == .ended {
       // how do I get the button text here? (i.e. "Item Name AAA")
       let button = sender.view as! UIButton
       print(button.titleLabel?.text)
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM