【问题标题】:Take Button label name to UILongPressGestureRecognizer, change var and return value to Button's label将Button标签名称取为UILongPressGestureRecognizer,更改var并返回值为Button的标签
【发布时间】:2020-03-02 09:51:56
【问题描述】:

请帮帮我。我尝试做的事情: 我有一些变量和按钮。当我长按按钮时,我希望弹出带有文本字段的警报。然后我想输入一些值(Int),然后将按钮的标签更改为(textField value + previous)。我想为几个按钮编写一个功能。我想做什么:

func addLongPressGesture(by sender: UIButton){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 1
    sender.addGestureRecognizer(longPress)
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizer.State.began {
        print("Long Press")

        var textField = UITextField()
        let alert = UIAlertController(title: "How much?", message: "", preferredStyle: .alert)
        let action = UIAlertAction(title: "Add", style: .default) { (action) in

            if let howMuch = textField.text {
                self.VARIABLE1 = self.VARIABBLE1 + Int(howMuch)!
                self.viewWillAppear(true)
            }
        }
        alert.addAction(action)
        alert.addTextField { (alertTextField) in
            textField = alertTextField
            textField.placeholder = "How much?"
        }
           present(alert, animated: true, completion: nil)
    }
}

我希望 VARIABLE1 根据我长按的按钮进行更改

【问题讨论】:

    标签: swift alert long-press


    【解决方案1】:

    听起来你已经声明了多个变量,每个按钮一个。这是您应该开始使用数组的好兆头。声明一个数组而不是多个变量:

    var totals = Array(repeating: 0, count: <however many buttons you have>)
    

    然后,为每个按钮分配不同的tag。您也可以在情节提要中进行设置。第一个按钮的标签为 0,第二个按钮的标签为 1,依此类推。

    longPress中,获取被gesture.view点击的按钮,获取标签。标签是你应该增加的数组的索引:

    if let howMuch = textField.text {
        self.totals[gesture.view!.tag] += Int(howMuch)! // Note: you should probably unwrap the Int? safely
        self.viewWillAppear(true) // Note: you shouldn't really call this yourself
    }
    

    【讨论】:

    • 谢谢! ? gesture.view!.tag 是我要找的!
    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2020-05-05
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多