Using Iboutlet from Another Class in Swift

How can I access IBOutlet in another class?

Your approach is incorrect. A view controller is initiated when it is displayed on the screen. One and only on view controller object can be displayed at one time. In your code, you are initiating a brand new view controller and set text to outlets. So that won't work. Instead, you need to set text to the text field on the existing instance of you view controller.

To do so, in the view controller that you want to receive text field content updates, register in notification center to receive a content update function calls.

NotificationCenter.default.addObserver(self, selector: #selector(listnerFunction(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

func listnerFunction(_ notification: NSNotification) {
if let data = notification.userInfo?["data"] as? String {
self.textField.text = data
}
}

Then in another view controller, if you want to send text to the above view controller and update text, simply post the data to notification center

let data:[String: String] = ["data": "YourData"]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: data)

Swift Accessing IBOutlet from another class

Try this

answerResultView.label.text = "some text"

Accessing IBOutlet from another class

You access a generic ViewController, but need to use an existing UIView. Do something like this:

class Test: UIViewController {

class func set_cornerRadius(yourView: UIView, radius: CGFloat) {
yourView.layer.cornerRadius = radius
}
}

That way, you pass the UIView you want to set the corner-radius.



Related Topics



Leave a reply



Submit