gpt4 book ai didi

ios - Xcode Playground 中的 ViewController - 帧报告双倍大小 (viewDidLoad)

转载 作者:行者123 更新时间:2023-12-01 19:56:54 26 4
gpt4 key购买 nike

我正在使用 UIViewController Xcode Swift 游乐场中的子类。 Controller 的 View 显然报告为双倍大小。我做错了什么还是我偶然发现了一个错误?

当我将一半宽度的黄色 subview 放入 View 时,它会覆盖整个宽度。

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())

enter image description here

最佳答案

您查看 Controller 的 View 将使用自动布局调整大小。自动布局传递将在 viewDidLoad 之后发生.如果您想通过引用 frame 以编程方式调整 subview 的大小在您的 View Controller 的 View 中,您应该将该代码移至 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())

关于ios - Xcode Playground 中的 ViewController - 帧报告双倍大小 (viewDidLoad),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42009613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com