How to make a TextFiled edit/equal a Label?

Updated on October 27, 2017 in Swift 3
3 on October 19, 2017

Hi!

I am wondering how to make a TextFiled edit a label. So, when a user types maybe “hello” into a textfield, it will make the connected label say “hello”. Thanks!

 

Swift 4

 
  • Liked by
Reply
0 on October 25, 2017

I’m sorry I can’t provide a code example at the moment, but what you want is pretty simple:

Make an outlet for the TextField and for the Label. Search for a method which says something like “(textfieldOutletName).textHasChanged” or “(textfieldOutletName).text.OnChange”.

Then you simply get the input from the TextField as a String and set this String as the Label.text (Label.text = textfield.text). As soon as I’ve got time I’ll lookup the name of the method for you… I haven’t used Swift for a while now…

 

  • Liked by
Reply
Cancel
1 on October 25, 2017

Here you go:

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var labelField: UILabel!
    
    @IBAction func textHasChanged(_ sender: UITextField) {
        labelField.text = textField.text
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
  • First you create the Outlets: textField & labelField
  • Second: Create the Event from the TextField (choose Event Changed as “Event”), I named the method “textHasChanged”
  • Set the labelField.text = textField.text

Easy 😉 Every time your textField changes, it will call the method and do whatever is in it.

on October 27, 2017

Thanks! I will be sure to try it!

Show more replies
  • Liked by
Reply
Cancel
Loading more replies