首页 > 解决方案 > 你如何在另一个函数中调用 UIButton 的“发送者”?

问题描述

我想在新功能中调用按下按钮的“发送者”。

我创建了一个通用函数来在我的计算器应用程序中执行标准操作。然后,我想为我有 IBAction 链接到的每种类型的运算符调用此函数。

func standardOperation(sender: UIButton) {

    if isOperator.contains(where: numberLabel.text!.contains) {
        numberLabel.text = sender.currentTitle
        firstValue = true
    } else {
        value = formatTextIntoDouble()
        numberLabel.text = sender.currentTitle
        firstValue = true
    }
}

@IBAction func divideButtonPressed(_ sender: UIButton) {
    operatorIndex = sender.currentTitle!

    standardOperation(sender: xx)

    operatorLabel.text = "\(prevValue) \(operatorIndex)"

}

但是,我似乎无法找到正确的发件人属性,因为我在每个 IBAction 中的标准操作(发件人:xx)中不断收到错误。调用被按下的 UIButton 的发送者的正确方法是什么?即,什么代替了xx?

我试过 UIButton 或 AnyObject 但都没有。

标签: swiftfunctionsender

解决方案


只需传入触发 divideButtonPressed 的发件人

标准操作(发件人:发件人)

我还会看一下强制解包选项和防御性代码。
示例:numberLabel.text!和


推荐阅读