Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created January 17, 2017 17:35
Show Gist options
  • Save azamsharp/d6adec07a9562ffd91536ed25c2cd77e to your computer and use it in GitHub Desktop.
Save azamsharp/d6adec07a9562ffd91536ed25c2cd77e to your computer and use it in GitHub Desktop.
Reflection to Create Views in Swift
struct LoginViewModel : ViewModel {
var userName :String
var password :String
}
class UIEngine<ViewModel> {
var viewModel :ViewModel
init(viewModel :ViewModel) {
self.viewModel = viewModel
}
func build() -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.lightGray
var y = 40
for property in Mirror(reflecting: self.viewModel).children {
print(property.label!)
if property.value is String {
let tb = UITextField(frame: CGRect(x: 0, y: y, width: 200, height: 44))
tb.backgroundColor = UIColor.darkGray
tb.placeholder = "Enter \(property.label!)"
view.addSubview(tb)
y += 40
}
}
return view
}
}
let loginVM = LoginViewModel(userName: "", password: "")
let view = UIEngine<LoginViewModel>(viewModel: loginVM).build()
class LoginViewController : UIViewController {
}
let loginVC = LoginViewController()
loginVC.view.addSubview(view!)
PlaygroundPage.current.liveView = loginVC
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment