I'm creating a greeting app that users can enter their names and the app return "Hello Jack!"
.
Error Message
Type 'UIViewController' has no member 'textFieldString'
How can I fix it, since I have already setted the variable on ViewController.swift.
textFieldString = textField.text!
Codes
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
[![enter image description here][1]][1]
var textFieldString = ""
@IBAction func pushButton(_ sender: UIButton){
textFieldString = textField.text!
textField.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultViewController = segue.destination as! ResultViewController
resultViewController.result = textFieldString
}
@IBAction func unwind(_ segue: UIStoryboardSegue) {
}
}
ResultViewController.swift
import UIKit
class ResultViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var result: String?
override func viewDidLoad() {
super.viewDidLoad()
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
label.text = "Hello\(result)! "
}
}
Reason:
textFieldString
is a property of ViewController
and not UIViewController
.
Solution:
Create a property result
in ResultViewController
and set it to label
in viewDidLoad()
.
class ResultViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var result: String?
override func viewDidLoad() {
super.viewDidLoad()
//rest of the code...
label.text = "Hello\(result ?? "")" //here...
}
}
Now in ViewController's
prepare(for:sender:)
method set result
to textFieldString
, i.e.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultViewController = segue.destination as! ResultViewController
resultViewController.result = textField.text
}