ViewController 在 Xcode Playground - 框架报告双倍大小 (viewDidLoad)
ViewController in Xcode Playground - frame reporting double sized (viewDidLoad)
我在 Xcode Swift 游乐场中使用 UIViewController
子类。控制器的视图显然报告为双倍大小。我是做错了什么还是遇到了错误?
当我将一半宽度的黄色子视图放入视图时,它覆盖了整个宽度。
Xcode 版本 8.2.1 (8C1002)
import UIKit
import PlaygroundSupport
class ViewController : UIViewController {
override func viewDidLoad() {
title = "Double Frame"
super.viewDidLoad()
view.frame // inspecting the frame size: 768 x 1024
let halfV = UIView(frame: CGRect(x: 0, y: 200,
width: Int(view.frame.width / 2),
height: Int(view.frame.width / 2)))
halfV.backgroundColor = UIColor.yellow
view.addSubview(halfV)
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: ViewController())
您的视图控制器的视图将使用自动布局调整大小。自动布局过程将在 viewDidLoad
之后发生。如果你想通过引用视图控制器视图的 frame
来编程调整子视图的大小,你应该将该代码移动到 viewDidLayoutSubviews
。例如:
class ViewController : UIViewController {
let halfV = UIView()
override func viewDidLoad() {
title = "Double Frame"
super.viewDidLoad()
view.frame // inspecting the frame size: 768 x 1024
halfV.backgroundColor = UIColor.yellow
view.addSubview(halfV)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
halfV.frame = CGRect(x: 0, y: 200,
width: CGFloat(view.frame.width / 2),
height: CGFloat(view.frame.width / 2))
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: ViewController())
我在 Xcode Swift 游乐场中使用 UIViewController
子类。控制器的视图显然报告为双倍大小。我是做错了什么还是遇到了错误?
当我将一半宽度的黄色子视图放入视图时,它覆盖了整个宽度。
Xcode 版本 8.2.1 (8C1002)
import UIKit
import PlaygroundSupport
class ViewController : UIViewController {
override func viewDidLoad() {
title = "Double Frame"
super.viewDidLoad()
view.frame // inspecting the frame size: 768 x 1024
let halfV = UIView(frame: CGRect(x: 0, y: 200,
width: Int(view.frame.width / 2),
height: Int(view.frame.width / 2)))
halfV.backgroundColor = UIColor.yellow
view.addSubview(halfV)
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: ViewController())
您的视图控制器的视图将使用自动布局调整大小。自动布局过程将在 viewDidLoad
之后发生。如果你想通过引用视图控制器视图的 frame
来编程调整子视图的大小,你应该将该代码移动到 viewDidLayoutSubviews
。例如:
class ViewController : UIViewController {
let halfV = UIView()
override func viewDidLoad() {
title = "Double Frame"
super.viewDidLoad()
view.frame // inspecting the frame size: 768 x 1024
halfV.backgroundColor = UIColor.yellow
view.addSubview(halfV)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
halfV.frame = CGRect(x: 0, y: 200,
width: CGFloat(view.frame.width / 2),
height: CGFloat(view.frame.width / 2))
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: ViewController())