Created
January 17, 2017 17:35
-
-
Save azamsharp/d6adec07a9562ffd91536ed25c2cd77e to your computer and use it in GitHub Desktop.
Reflection to Create Views in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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