ios - Swift/交付方法名称到 IBAction 以创建依赖项

标签 ios swift

在我的示例中,我有 3 个按钮。两个具有相同职责级别的按钮和第三个按钮依赖于第一个按钮。我希望第三个按钮调用按钮 1 或按钮 2 的方法,具体取决于按钮 1 或按钮 2 是否已被按下。

exampleMenu.buttnOne.addTarget(self, action: #selector(ViewController.firstBtnFunc(_:)), forControlEvents: .TouchUpInside)
exampleMenu.buttnTwo.addTarget(self, action: #selector(ViewController.secondBtnFunc(_:)), forControlEvents: .TouchUpInside)

我在想这样的事情来解决我的需求:

var currentButton:String = ""

func buttnOne(button: UIButton) {
    currentButton = "buttnOne"
}

func buttnTwo(button: UIButton) {
    currentButton = "buttnTwo"
}

@IBAction func thirdButtonAction(sender: AnyObject) {

    if currentButton == "buttnOne" {
        buttnOne()
    } else if currentButton == "buttnTwo" {
        buttnTwo()
    }
}

但那样我得到错误:Missing argument for parameter #1 in call

使用 ViewController.buttnOne() 给我错误:Use of instance member buttnOne on type ViewController;您是想改用 ViewController 类型的值吗?

我该如何解决我的问题?非常感谢您的帮助。

按要求编辑:

enter image description here

暂时不要介意界面。它处于测试阶段,尚未完成。但它给出了这个想法。 我希望用户选择一个类别。像液体一样。还有一个子类别,例如 ML(毫升)。

ML按钮有以下代码:

    func mlBtnFunc(button: UIButton!) {
    var numberInt:Double = Double(numberStr)!

    tableData = ["Mililiter", "Centiliter", "Liter", "Ounces", "Cups", "Gallons"]
    tableCounterData = ["\(numberInt) ml", "\(numberInt * 0.1) cl", "\(numberInt * 0.01) l", "\(numberInt * 0.0338135) oz", "\(numberInt * 0.00422676) cups", "\(numberInt * 0.000264172) gallons"]
    print(numberStr)

    currentButton = "mlBtnFunc"
}

现在我想让键盘部分的“执行”按钮再次调用该函数以重新计算用户输入的值。为了做到这一点,我现在这样调用它:

    @IBAction func enterKeyboardAction(sender: AnyObject) {

    if currentButton == "mlBtnFunc" {
        mlBtnFunc(nil)
    } else if currentButton == "clBtnFunc" {
        clBtnFunc(nil)
    }

}

你真的不能称之为最佳实践,但我不知道如何告诉 enterKeyboardAction 必须计算哪些值...任何建议将不胜感激。但目前应用程序正在执行我希望她执行的操作。

最佳答案

您的 buttnOnebuttnTwo 方法需要一个 UIButton 参数,但您在调用它们时并未提供该参数。如果它们有时收到 button 参数而有时没有,您可以使用可选的 UIButton 参数声明它们并使用 nil 调用它们,如下所示:

func buttnOne(button: UIButton!) {
    currentButton = "buttnOne"
}

func buttnTwo(button: UIButton!) {
    currentButton = "buttnTwo"
}

@IBAction func thirdButtonAction(sender: AnyObject) {

    if currentButton == "buttnOne" {
        buttnOne(nil)
    } else if currentButton == "buttnTwo" {
        buttnTwo(nil)
    }
}

关于ios - Swift/交付方法名称到 IBAction 以创建依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827127/

相关文章:

ios - 如何在自身或另一个 viewController 上运行 segue

ios - 具有组合条件的 DynamoDB 查询/扫描

ios - 以 iOS 9 作为部署目标的 Xcode 9.1 中的 iPhone 4s

objective-c - Objective-C : Create a new View in touches end

ios - AVAudioPlayer 被 MPMusicPlayerController 中断

ios - "Not running"状态下的远程通知

iphone - 检查更新版本

ios - 如何在 iOS13 上设置导航 Controller 中嵌入的状态栏的样式?

swift - 在 ScrollView 中嵌入 3 个 View Controller

xcode - 错误 "Thread 1: breakpoint 2.1"