快速更改UIViewController的视图

4
我创建了一个新的UIViewController,没有使用storyboard,这是我的代码。我想要改变我的视图框架,但这对我来说没有效果,我已经尝试在viewWillAppear中添加,但仍然不起作用,我知道可以添加一个新的UIView来实现它。我能否更改我的视图控制器的视图?感谢您的帮助。
import UIKit

class NewDetailViewController: UIViewController {

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.height
        let navBarHeight             = self.navigationController?.navigationBar.frame.size.height

        println("statusBarHeight: \(statusBarHeight) navBarHeight: \(navBarHeight)")

        // view
        var x:CGFloat      = self.view.bounds.origin.x
        var y:CGFloat      = self.view.bounds.origin.y + statusBarHeight + CGFloat(navBarHeight!)
        var width:CGFloat  = self.view.bounds.width
        var height:CGFloat = self.view.bounds.height - statusBarHeight - CGFloat(navBarHeight!)
        var frame:CGRect   = CGRect(x: x, y: y, width: width, height: 100)

        println("x: \(x) y: \(y) width: \(width) height: \(height)")

        self.view.frame           = frame
        self.view.backgroundColor = UIColor.redColor()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
1个回答

8
我发现在viewDidLayoutSubviews中添加这段代码对我有用。
override func viewDidLayoutSubviews() {
    let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.height
    let navBarHeight             = self.navigationController?.navigationBar.frame.size.height

    println("statusBarHeight: \(statusBarHeight) navBarHeight: \(navBarHeight)")

    // view
    var x:CGFloat      = self.view.bounds.origin.x
    var y:CGFloat      = self.view.bounds.origin.y + statusBarHeight + CGFloat(navBarHeight!)
    var width:CGFloat  = self.view.bounds.width
    var height:CGFloat = self.view.bounds.height - statusBarHeight - CGFloat(navBarHeight!)
    var frame:CGRect   = CGRect(x: x, y: y, width: width, height: height)

    println("x: \(x) y: \(y) width: \(width) height: \(height)")

    self.view.frame           = frame
    self.view.backgroundColor = UIColor.redColor()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接