2

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.

iosbegindevel
  • 307
  • 5
  • 20

4 Answers4

4

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")
    }
}
iOSDev
  • 326
  • 2
  • 10
0

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)
}
shubham
  • 611
  • 7
  • 16
The Pedestrian
  • 460
  • 2
  • 11
0

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.

mfiore
  • 321
  • 3
  • 16
0
@IBAction func btnClick(_ sender: UIButton{
    print(sender.titleLabel!.text!)
}
  • 1
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Jan 25 '23 at 09:25