Search code examples
iosswiftbuttonuibuttonpin-code

How to get UIButton name in swift5?


I am currently making a pin-code. I want to incorporate all the functions into one function, in order to integrate the button event function into one So I want to get the name of UIButton, but I don't know how.

@IBOutlet weak var oneButton: UIButton!
@IBOutlet weak var twoButton: UIButton!
...
var pinCodeNum : String! = ""
...

  @IBAction func OneButton(_ sender: UIButton) {
        pincodeLogic(sender)
    }

    func pincodeLogic(_ sender: UIButton) {
         // I want get value is (example : 'oneButton' or 'twoButton' or 'threeButton' more )
    }

As you can see from my code, I'm getting a 'sender' as a parameter I want to know the name of oneButton or twoButton using this parameter. How do I know?

screen

My number button consists of a button and a label.


EDit


  @IBAction func OneButton(_ sender: UIButton) {

        pincodeLogic(sender)
    }

    func pincodeLogic(_ sender: UIButton) {
         if let number = sender.currentTitle {
            print(number)
        }
    }

I can't see the print log.


Solution

  • You can compare the sender with your button instances.

    func pincodeLogic(_ sender: UIButton) {
        switch sender {
        case oneButton:
            print("oneButton pressed")
        case twoButton:
            print("twoButton pressed")
        default:
            print("unknown button pressed")
        }
    }