I'm just starting to learn Swift and I am building a simple application. The main page is simply a table:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let theData: [String] = ["BRDA", "HFH", "ENGRII", "HSSB", "GRVT"]
let cellReuseIdentifier = "cell"
@IBOutlet weak var tableView: UITableView!
@IBAction func unwindToHome(segue: UIStoryboardSegue) { }
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-600)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return theData.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = theData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath.row == 0) {
// segue to BRDA
performSegue(withIdentifier: "toBRDA", sender: nil)
} else {
print("Will add later! You clicked on \(theData[indexPath.row]).")
}
}
}
I made the first entry clickable and I got it to segue to another controller. This new controller has an UIImage object and it simply changes colours when you tap on it.
class BRDAController: UIViewController {
@IBOutlet weak var thePic: UIView!
override func viewDidLoad() {
super.viewDidLoad()
var tapGesture = UITapGestureRecognizer()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(BRDAController.didTap(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
thePic.addGestureRecognizer(tapGesture)
thePic.isUserInteractionEnabled = true
thePic.backgroundColor = UIColor.yellow
// Do any additional setup after loading the view.
}
@objc func didTap(_ sender: UITapGestureRecognizer) {
// User tapped at the point above. Do something with that if you want.
if thePic.backgroundColor == UIColor.yellow {
thePic.backgroundColor = UIColor.green
} else {
thePic.backgroundColor = UIColor.yellow
}
}
@IBAction func backButton(_ sender: Any) {
self.performSegue(withIdentifier: "goBackHome", sender: nil)
}
}
I used an unwinding segue to go back to my home but when I go back to the other controller, the state has been reset (the colour has been set to its default yellow). How do I go about getting my code to 'remember' its previous state?