我使用以下代码:
override func viewDidLoad() {
super.viewDidLoad()
let testView = UIView(frame: CGRectMake(0, 0, 320, 568))
testView.backgroundColor = UIColor.redColor()
self.view.addSubview(testView)
}
当 View 加载时不会发生。
但是在 IBAction 工作很不错
为什么?
最佳答案
首先尝试使用 swift 语法 CGRect(x:0, y:0, width:320, height:568) 并向我们展示创建 ViewController 的方式。
确保调用 viewDidLoad() 方法,因为此代码适用于我。
AppDelegate.swift
var window: UIWindow?
let viewController = ViewController()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let tabBarController = UITabBarController()
let controllers = [self.viewController]
tabBarController.viewControllers = controllers
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.rootViewController = tabBarController
self.window!.makeKeyAndVisible()
return true
}
ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
let testView = UIView(frame: CGRect(x:0, y:0, width:320, height:568))
testView.backgroundColor = UIColor.redColor()
self.view.addSubview(testView)
}
关于xcode - viewDidLoad() 中的 addSubview() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37810241/