Home > Enterprise >  Swift: How to display two buttons that have been pressed on a label
Swift: How to display two buttons that have been pressed on a label

Time:02-19

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
        }   
    }
}

CodePudding user response:

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 ?? "")
}

CodePudding user response:

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.)

  • Related