I am trying to transfer my object from HockeyDetailVC to my FavouritesVC using a button but my object is nil when I reach my second VC FavouritesVC. Why is it like that when I set the variable in my firstVC with my func transferObj()?
HockeyDetailVC
var item: CurrentPlayers?
override func viewDidLoad() {
super.viewDidLoad()
gonnaLoadView()
tableV.bounces = false
tableV.alwaysBounceVertical = false
favButton.layer.cornerRadius = 10
print(item) *//prints my current players object*
}
func transferObj() {
let otherVC = FavouritesVC()
otherVC.currentFav = item
print(item). *//prints my current player object*
}
#IBAction func addToFav(_ sender: Any) {
transferObj()
print("Favourite button Pressed")
}
FavouritesVC
var currentFav: CurrentPlayers?
override func viewDidLoad() {
super.viewDidLoad()
if currentFav == nil {
//display nil
self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
print(favArr) *//prints empty array*
print(currentFav) *//nil*
} else {
favArr.append(currentFav!)
print(favArr)
}
}
As #Martin stated, let otherVC = FavouritesVC() creates a new instance of the controller, but it is not the instance that you will eventually display. So you are effectively setting the currentFav of a random FavouritesVC that will never actually be displayed, while the one you eventually do navigate to has it's currentFav property still unset.
To set the appropriate FavouritesVC instance, you need to access it in one of several ways (depending on how you present it). If it is through a segue, then you can reference it in the prepare(for segue: sender:) method. (When you create a Cocoa Touch Class file, the below method template is pre-populated. As it states, reference the new view controller using segue.destination.)
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
Alternatively, if you create and present the new view controller programmatically with something like
// 1.
let otherVC = storyboard?.instantiateViewController(withIdentifier: "yourFavouritesVCIdentifier")
// 2.
// 3.
self.show(otherVC, sender: self)
you can insert your otherVC.currentFav = item at line // 2..
Related
I am making a quiz app and have three view controllers and I am also making use of a navigation controller. The controllers are: HomeController, LevelsController, PlayController.
The levels controller has 100 levels on it as buttons and all of them except level 1 are greyed out initially. As I complete levels, the other level buttons are unlocked and become clickable.
MY ISSUE:
This only works if I go back to the HomeController and press on the then navigate to the LevelsController again, it doesn't update instantly when I simply go back from the PlayController to the LevelsController.
This is my code in the levels controller:
import UIKit
class LevelsViewController: UIViewController {
var levels = [String]()
override func viewDidLoad() {
super.viewDidLoad()
for k in globalScore...99 {
// print("this is \(k)")
// print(levelButton)
levelButton[k].isEnabled = false
print("Have the levels updated??")
}
}
override func viewWillAppear(_ animated: Bool) {
for k in globalScore...99 {
levelButton[k].isEnabled = false
}
}
#IBOutlet var levelButton: [UIButton]!
#IBAction func levelSelect(_ sender: UIButton) {
self.level = sender.tag
performSegue(withIdentifier: "LevelToPlaySegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("my name is jacobson")
var vc2 = segue.destination as! PlayViewController
vc2.enteredLevel = self.level
}
}
My PlayController has a keyboard and an image that changes to a new image if the correct answer is input into a text field. I also have a score in the top right of the PlayController which is assigned to globalScore. as the global score increases, the levels page should have more levels available to the user when they go backwards from the PlayController to the LevelsController.
What you need to do is to change your logic and instead of using it on viewDidLoad, you should also add ViewDidAppear and ViewWillAppear, in order to call these method every time you open the viewController instead of doing it only the first time.
Jasc24 has answered this already but I'm writing exactly what worked for me.
I wrote this in my ViewDidLoad to make all levels except level 1 disabled:
for k in 1...99 {
levelButton[k].isEnabled = false
}
I wrote this after the ViewDidLoad to enable specific levels only:
override func viewWillAppear(_ animated: Bool) {
for k in 0...globalScore-1 {
levelButton[k].isEnabled = true
}
}
I am fairly new to Swift programming. Using Userdefaults I was trying to customize user behaviour. Below image is of my initial controller. I require to save userdefaults so that App remembers the user selection of button, (i.e. A or B). Can you assist to provide me a function that I use in viewDidLoad and it remembers the button selection and segues to its respective ViewController.
My code to perfrom segue if Button A or B is selected is
let parent = self.storyboard?.instantiateViewController(withIdentifier: "DashboardVC") as! DashboardVC
self.navigationController?.pushViewController(parent!, animated: true)
Yet it doesnt segue. It keeps loading my initial viewcontroller.
do like
set the tag for each button and create the common method for handle the function , for e.g
#IBAction func handle_Action(_ sender: UIButton) {
defaultName.set(sender.tag, forKey: "yourKeyName")
}
and in your class
class ViewController: UIViewController {
let defaultName = UserDefaults.standard
// finally access the integer in your Viewload
override func viewDidLoad() {
super.viewDidLoad()
let getVal = defaultName.integer(forKey: "yourKeyName") as Int
if getVal == 1{ //called by A
}else if getVal == 2{
//called by B
}else{ // not interactwithButton action }
}
I do have a View, in which I embedded a ContainerView. I fill my labels on my ContainerView the first time here
class UpperLower { ...
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
let PlayerInfoHeaderView = segue.destination as? PlayerInfoHeader
PlayerInfoHeaderView?.player1 = player1
PlayerInfoHeaderView?.player2 = player2
PlayerInfoHeaderView?.game = game
}
}
The Segue triggers the viewDidLoad() where I call the method updateUI()
class PlayerInfoHeader: UIViewController { ...
override func viewDidLoad() {
super.viewDidLoad()
updateUI(game: game)
}
func updateUI(game: Player.Game) {
player1NameLabel.text = player1.name
player2NameLabel.text = player2.name
switch game {
case .UpperLower:
player1PointsLabel.text = "Points: \(player1.points.UpperLower)"
player1WinrateLabel.text = "Winrate: \(player1.winrates.UpperLower) %"
player1RoundsWonLabel.text = "Rounds Won: \(player1.roundswon.UpperLower)"
player2PointsLabel.text = "Points: \(player2.points.UpperLower)"
player2WinrateLabel.text = "Winrate: \(player2.winrates.UpperLower)"
player2RoundsWonLabel.text = "Rounds Won: \(player2.roundswon.UpperLower)"
}
Now, after every round played, I also want to update my UI. I tried a lot of things, but I have no clue, how to trigger the UpdateUI() out of my UpperLower manually. I know that I need a reference to my embedded container view. But how can I get this reference outside of the segue context? Is there an easy way to solve my problem?
PS: I did all my UI work on the storyboard.
Set a weak property (to avoid retain cycle) in PlayerInfoHeader to keep a reference to your parent
weak var parentVC: UpperLower?
Set the property in prepareForSegue
PlayerInfoHeaderView.parentVC = self
I am working on an iOS application that is built around a Tab View Controller. I have created a "Contacts" tab, where a user can find and select a contact from a list. When the user selects the contact, it takes the contact's name and passes it to a different tab. That function is being done like so:
func passName(name: String) {
let navTab = self.tabBarController!.viewControllers![2] as! UINavigationController
let homeTab = navTab.viewControllers[0] as! MainController
homeTab.passedName = name
tabBarController?.selectedIndex = 2
}
Everything works as it should so far (name is loaded into text field). My issue is that the value seems to keep coming back every time I change tabs and then go back to my Home tab. For example, if I select "John" from my contacts, it will take me to the Home Tab and put John's name in a textfield. Let's say I delete the last two letters of the name, so now it is "Jo". If I load a different tab and come back, the name field has been reset to "John". It's as if the value gets re-passed every time I open the Home Tab. Also, every time I load the Home Tab after passing a name, my console prints: "Name Passed: John", so it shows that this is being processed every single time the tab appears. Here is my code for processing the name:
var passedName: String!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//Checks if name was passed to controller
if let validName = passedName {
print("Name passed: \(validName)")
nameTextField.text = validName
}
}
Am I passing the data incorrectly? I was thinking it might be because I have the above code being called in the viewWillAppear method, but that doesn't make sense, as essentially the data is only being passed one time from the Contacts tab. Thanks!
The problem is that you're not actually passing the value back to the original view. Apple's recommendation for passing information between classes is to use the delegate pattern. This allows the modal view to call the delegate class's function, which changes the name local to the original view because that function is declared in the original view's viewController. You can read more about the pattern in this tutorial, but I've also included a brief example relevant to your use case below.
mainViewController:
class namesTableViewController: UITableViewController, editNameDetailsViewControllerDelegate {
var name : String
#IBAction func editButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "editPerson", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "editPerson" { //Modal segue
let navController = segue.destination as! UINavigationController
let controller = navController.topViewController as! editNameViewController
controller.delegate = self
if let person = sender as? Person {
print("Sending person to edit")
controller.personToEdit = person
}
} else {
super.prepare(for: segue, sender: sender)
}
}
//Protocol function
func changeName(n: String, controller: UIViewController) {
name = n
dismiss(animated: true, completion: nil)
}
}
editNameViewController:
class editNameViewController: UIViewController {
#IBOutlet weak var personNameTextField: UITextField!
var personToEdit : Person?
weak var delegate : PersonTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
if personToEdit != nil {
personNameTextField.text = personToEdit?.name
}
}
// Button Actions
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
delegate?.personDetailsView(n: personNameTextField.text, controller: self)
}
}
Finally, the protocol class :
protocol editNameDetailsViewControllerDelegate : class {
func personDetailsView(n: String, controller: UIViewController)
}
Hope this helps.
The problem is "passedName" variable doesn't changed its value every time you edit it in your UITextField. Keep in mind that every time you change tabs, the UIViewController will call viewWillAppear and viewDidAppear. So your UITextField will always show passedName value once you select other tab and return.
I suggest that every time you edit the textfield you should update passedName value.
Sorry for my bad english.
I am getting "unexpectedly found nil while unwrapping an Optional value" because in my code below I am trying to assign value to webview before its initialize. I am trying to transition from Master to Detail view controller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
Detail View Code:
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detailContent = detailItem?.valueForKey("content") as? String{
self.webView.loadHTMLString(detailContent as String, baseURL:nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
It is failing because my Webview in Nil. How do I come around this situation where my outlets are not initialized while setting them.
Please help.
Thanks.
Stop and think about the order in which things happen:
prepareForSegue - The destination view controller exists, but that's all. It has no view and its outlets have not been set. You can set its non-outlet properties but that's all you can do.
The segue starts to happen.
The destination view controller gets viewDidLoad. Now it has a view and its outlets are set.
The segue completes and the destination view controller gets viewWillAppear: and later, viewDidAppear:. Now its view is actually in the interface.
So clearly you cannot permit configureView to assume that the web view exists, because the first time it is called, namely in prepareForSegue, it doesn't exist. configureView needs to test explicitly whether self.webView is nil, and if it is, it should do nothing:
func configureView() {
// Update the user interface for the detail item.
if self.webView == nil { return } // no web view, bail out
if let detailContent = detailItem?.valueForKey("content") as? String{
self.webView.loadHTMLString(detailContent as String, baseURL:nil)
}
}
After that, everything will be fine. viewDidLoad will subsequently be called, and configureView will be called again - and this time, both detailItem and the web view exist, so all will be well.