user8054720
user8054720

Reputation:

Change the text of a label with a button in iOS

Firstly, let me say I'm new to Swift and Xcode. I have a label that displays some text and I want that text to change when a button is pressed.

Here is the code in the UIViewController:

var txt = "Hey"

@IBOutlet weak var Text: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    showText()
}

func showText(){
    Text.text = txt
}

@IBAction func Button(_ sender: Any) {
    txt = "Hello"
}

The buttons and labels are correctly linked to their main.storyboard counterparts. When I run this and press the button the text doesn't change.

Upvotes: 6

Views: 12807

Answers (5)

Dixit Akabari
Dixit Akabari

Reputation: 2547

just change your IBAction like this.

@IBAction func Button(_ sender: Any) {
    txt = "Hello"
    showText()
}

Upvotes: 0

iOS Geek
iOS Geek

Reputation: 4855

Change Text of label with button just need to pass the text in label;

//Outlets  
@IBOutlet weak var firstLabel: UILabel!        
@IBOutlet weak var secondLabel: UILabel!


 //Button Action
 @IBAction func textChabge(_ sender: Any) {

            firstLabel.text = "newText"

            secondLabel.text = "newText"

  }

Upvotes: 0

Mitul.Patel
Mitul.Patel

Reputation: 252

change your code as per below

var txt = "Hey"

@IBOutlet weak var Text: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showText()
}

func showText(){
Text.text = txt
}

@IBAction func Button(_ sender: UIButton) {
txt = "Hello"
showText()
}

Upvotes: 0

Nicolas Miari
Nicolas Miari

Reputation: 16256

I will add that it is more flexible and perhaps elegant to have your showText() method take the actual text to show as an argument, instead of depending on some internal state (the value of the property txt: String, that isn't immediately evident at the call site) to accomplish its task:

@IBOutlet weak var textLabel: UILabel!

func showText(_ text: String){
    self.textLabelabel?.text = text

    // (optional chaining to avoid crash if accidentally 
    // called before viewDidLoad())
}  

@IBAction func buttonAction(_ sender: Any) {
    self.showText("Hello")  // From here it is clear what text will be shown
}

Upvotes: 1

vacawama
vacawama

Reputation: 154701

viewDidLoad() is only called one time when the ViewController is created. showText() needs to be called after txt is set if you want to display it. One way to automate this is to add a property observer to txt to call showText() when txt is updated:

var txt = "Hey" {
    didSet {
        showText()
    }
}

Upvotes: 2

Related Questions