I am working on building framework for a widget. I have two files as follows:
widgetBuilder.swift
and
webWidget.swift
widgetBuilder.swift
is file with getters and setters that takes certain values from the app that is going to use this widget framework.
Code from widgetBuilder.swift
import Foundation
class WidgetBuilder {
private var userId: String!
private var emailId: String!
public func setuserId(userId: String) -> WidgetBuilder{
self.userId = userId
return self
}
public func setEmailId(emailId: String) -> WidgetBuilder{
self.emailId = emailId
return self
}
public func build() -> WidgetBuilder{
// Wanted to load the webview from here
}
}
Once the initialization is done I would call the build function, I wanted to load the ViewController of webWidget.swift
Code from webWidget.swift
class webWidget: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
self.loadWebView()
}
public func loadWebView(){
let url = URL(string: "https://www.google.com")!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
public func loadWidgetScreen() {
//Something is not correct here
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "WidgetController")
self.present(controller, animated: true, completion: nil)
}
}
How do I load the webWidget view from the widgetBuilder.swift
and pass some data along ?
So this is how I solved , Posting it, might be helpful for somebody looking to load a ViewController from a swift file.
Once I call the the build()
from my swift file , it has to load the view,
Added a var
that gets the ViewController instance from the parent view that wants to load this widget.
Inside the widgetBuilder.swift
private var clientView: UIViewController?
public init(_ viewController:UIViewController){
self.clientView = viewController;
}
Then,
public func build(){
// Widget() creates ViewController instance , this viewcontroller is mapped to a widget.xib file
let controller: UIViewController = Widget() // Creating the instance of the view class
self.clientView?.addChild(controller) // self.clientView is the ViewController instance that wants to load widget view
self.clientView?.view.addSubview(controller.view)
controller.view.frame = (clientView?.view.bounds)!
controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
controller.didMove(toParent: clientView)
}