skip to Main Content

I am trying to get buttons (they are numbers) when pressed to show two digits in the label, currentChannelLabel, I created. I have been messing around with this and I can either get one number to show, or I get two of the same number to show. How do I fix my code so I get one number to show, then a second number? After this, if another button is selected, it will show the first number again and then the second. For example:

(button 1 is pressed)
currentChannelLabel: 1
(button 2 is pressed)
currentChannelLabel: 12
(button 3 is pressed)
currentChannelLabel: 3
(button 4 is pressed)
currentChannelLabel: 34

here is my code:

 @IBAction func channelNumbers(_ sender: UIButton) {
    var number = ""
    if let pressed = sender.currentTitle {
        number = "(pressed)"
        currentChannelLabel.text = number
        if let pressed2 = sender.currentTitle{
            number += "(pressed2)"
            currentChannelLabel.text = number
        }   
    }
}

2

Answers


  1. The problem with your code is that pressed2 will always be equal to pressed, because it’s not going to change within the body of the function — instead, when the second button is pressed, the function is called again.

    Here’s some code that should do what you want:

     @IBAction func channelNumbers(_ sender: UIButton) {
        guard let number = currentChannelLabel.text else {
            currentChannelLabel.text = sender.currentTitle
            return
        }
        currentChannelLabel = (number.count == 1 ? number : "") + (sender.currentTitle ?? "")
    }
    
    Login or Signup to reply.
  2. Your code doesn’t make much sense. You have two nested if let statements. Either the first will fail, or both will succeed.

    You need something like this:

    @IBAction func channelNumbers(_ sender: UIButton) {
        if let pressed = sender.currentTitle {
            let oldLabelText = currentChannelLabel.text ?? ""
            currentChannelLabel.text = oldLabelText + pressed
        }
    }
    

    The string you get in pressed will be the title of the button that was pressed. Then you append that to previous text from the label, and put the result back into currentChannelLabel.text.

    (Note that storing your string in currentChannelLabel.text is not ideal. You should really keep a string var in your view controller, append to that, and copy that string into currentChannelLabel.text. (View objects should not hold state. They should display info to the user and collect input from the user.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search