Get button pressed id on Swift via sender

后端 未结 15 1094
广开言路
广开言路 2020-12-01 04:21

So I have a storyboard with 3 buttons I want to just create 1 action for all those 3 buttons and decide what to do based on their label/id...

Is there a way to get s

15条回答
  •  失恋的感觉
    2020-12-01 05:18

    If you want to create 3 buttons with single method then you can do this by following code...Try this

    Swift 3
    Example :-

    override func viewDidLoad()
    {
        super.viewDidLoad()
        Button1.tag=1
        Button1.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
        Button2.tag=2
        Button2.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
        Button3.tag=3
        Button3.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
    
    }
    
    func buttonClicked(sender:UIButton)
    {
        switch sender.tag
        {
            case 1: print("1")     //when Button1 is clicked...
                break
            case 2: print("2")     //when Button2 is clicked...
                break
            case 3: print("3")     //when Button3 is clicked...
                break
            default: print("Other...")
        }
    }
    

提交回复
热议问题