I wanted to test some Swift code but I found a problem I never saw before. When I launch the application on the iPhone simulator or on a real device, for some reason the views are not being displayed... I only did two things just after creating the project:
- Write some code on the AppDelegate file to create the window and then choose the initial controller.
- Create a simple UITextView on the viewDidLoad method of that controller
The only thing I'm getting is a full white screen, without any text on the center as it was supposed to be. I used a print("Called") to verify that viewDidLoad is being executed, and in fact, it is so... Where is the problem?
AppDelegate.swift:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = window ?? UIWindow()
window?.backgroundColor = UIColor.white
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
}
extension CGRect {
init(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) {
self.init(x: x, y: y, width: w, height: h)
}
}
ViewController.swift:
class ViewController: UIViewController {
override func viewDidLoad() {
print("Called")
let tv = UITextView()
tv.text = "Hola Mundo"
tv.sizeToFit()
tv.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(tv)
NSLayoutConstraint.activate([
tv.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
tv.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
])
}
}