How to get UIButton name in swift5?

2.4k Views Asked by At

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.

4

There are 4 best solutions below

3
iOSDev On BEST ANSWER

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")
    }
}
0
The Pedestrian On

if you want to access the button action to perform some specific task.Just put a tag with your each button and add the same target to all.

@IBAction func btnAction(_ sender: UIButton) {
switch sender.tag {
case 1:
    print("oneButton pressed")
case 2:
    print("twoButton pressed")
default:
    print("unknown button pressed")
 }
}

If you need just to print the button title the do the following.

@IBAction func btnAction(_ sender: UIButton) {
   print(sender.titleLabel?.text! as! String)
}
1
mfiore On

To access the contents of the label present in the button using the sender, this is an example:

@IBAction func OneButton(_ sender: UIButton) {
   print(sender.titleLabel?.text)
}

so you could do this:

@IBAction func OneButton(_ sender: UIButton) {

        pincodeLogic(sender)
  }

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

I hope I've been there for you. Let me know.

1
Donovan Whysong On
@IBAction func btnClick(_ sender: UIButton{
    print(sender.titleLabel!.text!)
}