swift nil when setting the value of text field - ios

this is my prepare for segue code
switch segue.identifier! {
case SegueIdentifiers.SecondUIViewController.rawValue:
print("\(SegueIdentifiers.SecondUIViewController.rawValue)")
let secondViewController = segue.destinationViewController as? SecondViewController
secondViewController!.resultTextField.text = "asdfasdf"
//break
default:
print("nothing sweetheart")
break
}
i got nil exception on this line
secondViewController!.resultTextField.text = "asdfasdf"
why ? the text field already there
this is the second view controller
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var resultTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}

Your outlets are not set until viewDidLoad. Before that they are all nil. This is why they are optionals. Thus when you try to access them from prepareForSegue they are still nil.
I recommend you add a new property to your view controller, and set that from prepareForSegue. Later when your outlets are set you can update your text field.
// in prepareForSegue
let secondViewController = segue.destinationViewController as? SecondViewController
secondViewController!.resultText = "asdfasdf"
And then in your view controller
class SecondViewController: UIViewController {
var resultText: String = "" {
didSet {
resultTextField?.text = text
}
}
#IBOutlet weak var resultTextField: UITextField! {
// Will be set once in viewDidLoad.
// Whenever that happens update text.
didSet {
resultTextField.text = resultText
}
}
}
Now you can modify your text field from the resultText property even before the outlets are set, and they will be updated when set thanks to the didSet property observer.

Related

How can I change UILabel.text from different swift file?

I am getting nil value error when I try to change UIlabel from a different swift file other than ViewController.
//ViewController.swift
import UIKit
class MainViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
myLabel?.text = "foo"
}
func label(stringVal: String? = nil){
myLabel?.text = stringVal!
}
}
//Source.swift
//Do working here and get a string value from struct
// I saved that string in stringValue
let VC = MainViewController()
VC.label(stringVal: stringValue!)
Please let me know what am I doing wrong.
View controller controls are not created in constructor, it is expected to be null. You need to show that view controller before to run label method and avoid the error.
A valid option would be to set an internal variable in the constructor and in viewDidLoad, when the label is already created, you could do
myLabel.text = stringValue // stringValue is comes from constructor.

What should I change in my code to make textfield in cell not to be nil after dismiss VC

Community!
I have some issue.
code:
protocol CellDelegate: class { }
class Cell: UITableViewCell {
.....
#IBOutlet weak var valueTextField: UITextField!
weak var delegate: CellDelegate?
.....
}
didSelectRowAt indexPath presents my ContainerView by overFullScreen, where I have:
class ContainerViewController: UIViewController {
.....
#IBOutlet private weak var fromTextField: UITextField!
#IBOutlet private weak var toTextField: UITextField!
#IBAction private func performChange(_ sender: UIButton) {
if let from = Int(fromTextField.text!), let to = Int(toTextField.text!) {
let cell = Cell()
cell.delegate = self
cell.valueTextField = "\(from) - \(to)"
self.dismiss(animated: false, completion: nil)
}
}
.....
}
extension ContainerViewController: CellDelegate { }
printDebug tells me that performChange sending my data well to other class, but cell.valueTextField is being nil when ContainerViewController dismiss and app crash
I know that I can make valueTextField.text = "1 - 5" //example from 1 to 5
with help of alert, but I need to make it with other viewController.
Please help me
You shouldn't use
let cell = Cell()
but instead add a delegate to the previous vc when you present the containervc (inside didSelectRowAt) and send the data before the dismiss , then change the array model of the table and finally refresh the table

Swift 3 - Delegate always returns nil value

UPDATED:
I have designed custom tabBar using buttons. I have 3 tabs,
First tab has Messages icon, Second has Profile icon and Third has Photos icon. For third tab button, I have used uiCollectionView() where I need to set images.
For the Third tab's ViewController,there is one condition that I need to check, before changing the title of the first tab button. If messages JSON array is not empty then set "new message" title on the first tab button, else the Messages icon won't change.
There is one ParentTabViewController which has these 3 tabs, I have used uiView, where I change the content according to the tab buttons pressed. I tried to access the values of 3rd tab in ParentTabViewController by using delegate, but the delegate is always nil. I did like this:
class ParentTabViewController: UIViewController,MessageDelegateProtocol{
#IBOutlet weak var contentView: UIView!
#IBOutlet var tabBarButtons : [UIButton]!
#IBOutlet weak var firstTabButton: UIButton!
var MessageVC : UIViewController!
var ProfileVC : UIViewController!
var PhotosVC : UIViewController!
var viewControllers : [UIViewController]!
var message : String!
var selectedIndex:Int = 0
var photoVC = PhotosVC()
override func viewDidLoad() {
super.viewDidLoad()
photoVC.newMessageDelegate = self
let storyBoard = UIStoryboard(name:"Main", bundle:nil)
MessageVC = storyBoard.instantiateViewController(withIdentifier: "messagevc")
ProfileVC = storyBoard.instantiateViewController(withIdentifier: "profile")
PhotosVC = storyBoard.instantiateViewController(withIdentifier: "photos")
viewControllers = [MessageVC, ProfileVC, PhotosVC]
tabBarButtons[selectedIndex].isSelected = true
didPressTabs(tabBarButtons[selectedIndex])
}
#IBAction func didPressTabs(_ sender: UIButton)
{
let previousIndex = selectedIndex
selectedIndex = sender.tag
tabBarButtons[previousIndex].isSelected = false
let previousVC = viewControllers[previousIndex]
previousVC.willMove(toParentViewController: nil)
previousVC.removeFromParentViewController()
previousVC.view.removeFromSuperview()
sender.isSelected = true
let presentVC = viewControllers[selectedIndex]
addChildViewController(presentVC)
presentVC.view.frame = contentView.bounds
contentView.addSubview(presentVC.view)
presentVC.didMove(toParentViewController: self)
if selectedIndex == 2{ // this is what I thought of doing.Correct me if wrong.
// check the condition
// if messagesArray != nil
// set the first tab title "new message"
}
else{
// do not change the button image
}
}
func sendMessage(message : String)
{
self.message = message
print("message........", self.message, "\n\n")
}
}
Here is the View Controller for 3rd tab:
import UIKit
protocol MessageDelegateProtocol:class {
func sendMessage(message : String)
}
class PhotosVC: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate{
#IBOutlet weak var collectionView: UICollectionView!
var userMessageArray = [UserMessageClass]() // array of model class
var newMessage : String!
weak var newMessageDelegate : MessageDelegateProtocol?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
loadData() // function to get json reponse
}
// implement collectionView delegate and dataSource methods
func getData(newMsg : UserMessageClass) //func to get values from model class
{
newMessage = newMsg.messageString // here I get the "new message" String
newMessageDelegate?.sendMessage(message: newMessage)
} enter code here
func loadData()
{
// get json response. And pass the payload to UserMessageClass using that class's array
userMessageArray.append(UserMessageClass(dict : jsonData))
var msgData = UserMessageClass(dict: jsonData)
getData(alarm: msgData)
}
}
I tried searching a lot about accessing tab buttons in another VC, but didn't find any nearby approach as such. Also I am not able to figure out why delegate is always nil. Suggestions or Help would be grateful. Many Thanks :)
The problem is the following line.
let firstTab = storyBoard.instantiateViewController(withIdentifier: "parentVC") as! ParentViewController
You are probably expecting it to give you the instance of ParentViewController which you have setup initially. However, it will give you the instance of a newly initiated ParentViewController which is not what you want.
To counter this problem you can either make use of a delegate or completion block defined which will be defined inside your ParentViewController class.
Update:
Try adding PhotosVC.newMessageDelegate = self under the line
PhotosVC = storyBoard.instantiateViewController(withIdentifier: "photos")
Also change var PhotosVC : UIViewController! to var photosVC: PhotosVC!
This should work now.

Swift how to update label in previous view controller

I want to update the label in my DashboardViewController from my AccountViewController when the back button is pressed in AccountViewController.
I have tried passing back a variable from 2nd view to 1st view and updating the label in viewDidLoad and in viewWillAppear but it never updates the label when the 1st view is back on screen.
I tried creating a function in 1st view to update the label with a string passed into the function and calling that function from 2nd view but it says that the label is nil so it couldn't be updated.
My latest attempt was to create a delegate but that didn't work either.
Here is my delegate attempt.
class DashboardViewController: UIViewController, AccountViewControllerDelegate {
#IBOutlet weak var welcome_lbl: UILabel!
func nameChanged(name: String){
var full_name = "Welcome \(name)"
welcome_lbl.text = "\(full_name)"
}
override func viewDidLoad() {
super.viewDidLoad()
AccountViewController.delegate = self
}
}
And then in my AccountViewController I have this
protocol AccountViewControllerDelegate{
func name_changed(name: String)
}
class AccountViewController: UIViewController, UITextFieldDelegate {
var info_changed = false
static var delegate: AccountViewControllerDelegate!
#IBAction func back_btn(sender: AnyObject) {
if(info_changed){
AccountViewController.delegate.name_changed(name_tf.text!)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
Did I mess up the delegate process somehow ? Or is there an easier way to do this?
First. Your delegate should be a normal property of AccountViewController. There is no need to update your name when user press back. You can change DashboardViewController`s name when user change name in AccountViewController. When user go back to DashboardViewController. It`s already show the changed name.
protocol AccountViewControllerDelegate{
func name_changed(name: String)
}
class AccountViewController: UIViewController, UITextFieldDelegate {
var delegate: AccountViewControllerDelegate?
// when user change name through textfield or other control
func changeName(name: String) {
delegate?.name_changed(name)
}
}
Second. When DashboardViewController show AccountViewController. I think it should be push. Set DashboardViewController instance be AccountViewController instance`s delegate.
class DashboardViewController: UIViewController, AccountViewControllerDelegate {
#IBOutlet weak var welcome_lbl: UILabel!
func nameChanged(name: String){
var full_name = "Welcome \(name)"
welcome_lbl.text = "\(full_name)"
}
// present or push to AccountViewController
func showAccountViewController {
let accountViewController = AccountViewController()
accountViewController.delegate = self
// do push view controller
}
}

#IB Action function inside of viewdidload in Swift

Is it possible to have an #IB Action function inside of viewDidLoad() ?
The action is a simple one - a Stepper that increases other label.text values accordingly. However, the values that the stepper needs to work with depend on the return content of a url - which are only known after the viewDidLoad() of course.
So I think I can't have the IBaction way up on top before the viewDidLoad(), and the error I get if I try to do my IB action inside of the viewDidLoad() is:
"Only instance methods can be declared ‘IBAction' ”
EDIT
Let me clarify myself, sorry for the confusion. I know I need an outlet to get the UIStepper values from. I have that:
#IBOutlet weak var stepper: UIStepper!
I then have an action also connected to same UIStepper that will increase/decrease value of a label's text (new_total) accordingly:
#IBOutlet weak var new_total: UILabel!
#IBAction func step_up_pass(sender: AnyObject) {
new_total.text = "\(Int(stepper.value))"
}
However, I want to start out with a value (todays_price) I'm getting back from a json request and use that as a starting point, to multiply it using the stepper and put the multiplied value into the label's text.
I have a struct in a separate file that defines my object so:
struct PassengerFromOtherBus {
var fname: String?
var lname: String?
var todays_price: Int?
init(json: NSDictionary) {
self.fname = json["fname"] as? String
self.lname = json["lname"] as? String
self.todays_price = json["todays_price"] as? Int
}
}
So later on in the view controller, inside of the viewDidLoad(), after connecting to the URL and then parsing it using NSJSONSerialization and a bunch of other code here (that I don't need to confuse you with) I finally have my value todays_price. So my question is, how do I get my action to use that value when it's only known inside of my viewDidLoad()? Xcode will not even let me connect the IBAction to anywhere inside the viewDidLoad function!
This is not done with an Action but with an Outlet. Connect the Stepper from IB as an Outlet to your ViewController. Then just set the values of the Stepper in ViewDidLoad.
I would never go directly from a UIStepper.value to UILabel.text.
Use an intermediary variable to store the value.
Do the same for the return from the JSON. By setting a didSet function on those variables you can update the UI when any of the values is updated.
class FirstViewController: UIViewController {
var todays_price: Int = 0 {
didSet { // didSet to trigger UI update
myLabel.text = "\(stepperValue * todays_price)"
}
}
var stepperValue : Int = 1 {
didSet { // didSet to trigger UI update
myLabel.text = "\(stepperValue * todays_price)"
}
}
#IBOutlet weak var myStepper: UIStepper!
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
//
let returnValueFromJson = 10
todays_price = returnValueFromJson
}
#IBAction func stepperUpdate(sender: AnyObject) {
stepperValue = Int(myStepper.value)
}
}
Just add a variable to the top of your view controller to hold the value from your json request. Then in viewDidLoad you update that variable, and then you can use it to set your label and inside the IBAction (that doesn't have to be inside viewDidLoad).
So you would do something like this:
class WhateverViewController: UIViewController {
var todays_price: Int!
override func viewDidLoad() {
super.viewDidLoad()
todays_price = // The value you got from json goes here
new_total.text = "\(todays_price)"
}
#IBAction func step_up_pass(sender: AnyObject) {
new_total.text = "\(Int(stepper.value) * todays_price)"
}
}

Resources