【问题标题】:UIButton doing different tasksUIButton 执行不同的任务
【发布时间】:2015-06-17 21:57:27
【问题描述】:

如何让 UIButton 在每次快速按下时执行不同的操作。我试过制作两个重叠的按钮,一个在单击时隐藏但不起作用。

编辑:没关系,我发现我可以为静音/播放按钮执行此操作

If backgroundaudio.play

背景音频.pause 别的 Backgroundaudio.play

【问题讨论】:

  • 您可以在 IBAction 函数中调用您喜欢的任何其他函数。只需使用一些条件来确定使用哪个函数
  • 你能证明我怎么做?
  • 我会发布一个简短的答案

标签: swift uibutton


【解决方案1】:

您可以通过两种不同的方式做到这一点:

更改按钮的目标:

添加目标:

button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

移除一个目标:

button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

或者在你的动作函数中有一个逻辑语句:

button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

func buttonAction(sender: UIButton!)
{ 
     //your conditions go here
}

【讨论】:

  • 谢谢大家?非常感谢
  • 如果他们有帮助,你应该接受别人的。
【解决方案2】:

例如:每隔一段时间做一次你可以写的东西:

func oneThing() {
    // Do your stuff
}

func otherThing() {
    // Do other stuff
}

var shouldDoOtherThing = false

@IBAction func clicked(sender: UIButton) {
    if shouldDoOtherThing {
        otherThing()
    } else {
        oneThing()
    }
    shouldDoOtherThing = !shouldDoOtherThing
}

你也可以在 if 语句中做你想做的事情,比如

var shouldDoOtherThing = false

@IBAction func clicked(sender: UIButton) {
    if shouldDoOtherThing {
        // Do other stuff
    } else {
        // Do your stuff
    }
    shouldDoOtherThing = !shouldDoOtherThing
}

或者你可以使用其他任何东西来改变应该执行的代码(它们被称为控制语句)

【讨论】:

    【解决方案3】:

    我刚刚对此进行了测试。你只需要一个按钮。你可以随心所欲地做任意多的事情

    @IBAction func button_click(sender: AnyObject) {
    
        var randomNumber = Int(arc4random_uniform(5) + 1) // generates random number 1 - 5
    
        println(randomNumber)
    
        switch randomNumber { // perform method depending on what random number was generated
    
        case 1 :
            funcOne() // Run this method
            println("Pressed 1")
    
        case 2:
            funcTwo() // Runs this method
            println("Pressed 2")
    
        case 3:
            funcThree() // Runs this method
            println("Pressed 3")
    
        case 4:
            funcFour() // Runs this method
            println("Pressed 4")
    
        case 5:
            funcFive() // Runs this method
            println("Pressed 5")
    
        default:
            println("do nothing")
        }  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多