Swift - determine which button was pressed with switch

前端 未结 5 631
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 01:04

I have 4 buttons that call one function. Depending on which button was pressed i need to hide button inside of function that called after pressing.I dont know which button w

5条回答
  •  爱一瞬间的悲伤
    2020-12-17 01:37

    I know this has been answered, but if you set this up in IB, then I would recommend you check if the button was pressed by using the @IBOutlet variables as cases.

    class SomeView: UIView {
        @IBOutlet weak var buttonA: UIButton!
        @IBOutlet weak var buttonB: UIButton!
        @IBOutlet weak var buttonC: UIButton!
    
        @IBAction func didHitButton(_ sender: UIButton) {
            switch sender {
            case buttonA:
                doThis()
            }
            case buttonB:
                doThat()
            }
            case buttonC:
                doThisAgain()
            }
            default:
                doNothing()
            }
        }
        ...
    }
    

    Now you hook up the buttons in your NIB to each @IBOutlet, and all of the buttons to the one @IBAction didHitButton.

    This is pretty straight forward, and you don't have to worry about tags or changing names.

提交回复
热议问题