0

I have a problem when after use UILabel with optional value after show custom dialog by xib. after data passed on protocol. it UILabel can't change value because it first time i was develop in swift.

label?.text = data

and 'data' get from pass a protocol value.

But in Android Java. if i used

label.setText(data)

value will be change in label.

maybe, if you can tell me why didn't work it? i was grateful. thank you for help me..

Michael Fernando
  • 117
  • 1
  • 10

2 Answers2

1

Perhaps it might be a main thread problem for UI updates. Try and see if this works:

DispatchQueue.main.asnyc {
   label?.text = data
}
  • it didn't work inside protocol, sir. although i used optional value in secondary class in xib – Michael Fernando Jul 11 '21 at 02:24
  • addition my comment. when i print label?.text, its shown nil value although i used .layoutIfNeeded() or .setNeedsDisplay() @infiniteObj – Michael Fernando Jul 11 '21 at 03:05
  • @MichaelFernando When it is showing nil, that means your protocol is not receiving the string from the delegate object that called that protocol function. Have you set the "delegate = self" for the delegate method that is calling your protocol? I sometimes make a mistake of missing this out. – infiniteObj Jul 11 '21 at 05:07
  • i think in secondary class. i have delegate it self such as labellist.delegate = self. @infiniteObj – Michael Fernando Jul 11 '21 at 05:18
  • yeah, it's worked. i found this my problem in my secondary class when i init variable in protocol. thank you very much @infiniteObj – Michael Fernando Jul 11 '21 at 06:00
0

suppose you need data back from ViewController2 to ViewController1

ViewController1.swift

protocol VC2Delegate {
    func getString(newString:String)
}

class ViewController1: UIViewController, VC2Delegate {
    @IBAction func btnJumpOnVC2(_ sender: Any) {
        guard let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as? ViewController2 else {return}
        vc2.modalPresentationStyle = .fullScreen
        vc2.dataDelgate = self
        self.present(vc2, animated: true, completion: nil)
    }    
 
    func getString(newString: String) {
        label?.text = newString
    }
}

ViewController2.swift

class ViewController2: UIViewController {
    var dataDelgate : VC2Delegate?

    @IBAction func btnBackToVC1(_ sender: Any) {
        dataDelgate?.getString(newstring:"Perfect")
        dismiss(animated: true, completion: nil)
    }    
}

checkout and find what you miss in your code.

jatin fl
  • 157
  • 6