xcode - viewDidLoad() 中的 addSubview() 不起作用

标签 xcode swift

我使用以下代码:

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/

相关文章:

c++ - Xcode All Exceptions 断点 - 忽略某些 C++ 异常

ios - ld : framework not found FileProvider for architecture x86_64 in Xcode 8. 3.2

ios - 无法使用 Spotify iOS 应用程序远程 SDK 禁用自动播放

ios - Swift - 如何发送内容类型为 "x-www-form-urlencoded"的 POST 请求

swift - Xcode Siri 意图 : How to pass a variable from Intent Handler to IntentUI ViewController without including it in the response

ios - 使用 swift 运行 url

ios - 使用页面 View Controller 快速创建向导

xcode - 如何在 Xcode 中将 NSClickGestureRecogniser 与 Swift 一起使用?

iphone - 更改父 View Controller 容器中的标签

xcode - 我想使用 '1.1.0' 的版本 `Alamofire-SwiftyJSON`