gpt4 book ai didi

ios - 如何在没有 Storyboard的情况下设置 ViewController 的框架

转载 作者:搜寻专家 更新时间:2023-11-01 06:51:38 25 4
gpt4 key购买 nike

我想在不使用 Storyboard的情况下使用 ViewController 创建一个 View (例如 100x100)。我想知道声明 ViewController 框架的最佳方法是什么。

我试过:

class MyLittleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}
}

我试图在我的 MainViewController 上看到这个 View :

override func viewDidLoad() {
super.viewDidLoad()

let myLittleView = MyLittleViewController()
myLittleView.willMove(toParent: self)
myLittleView.view.translatesAutoresizingMaskIntoConstraints = false
myLittleView.view.backgroundColor = .red
view.addSubview(myLittleView.view)
// enable auto-sizing (for example, if the device is rotated)
myLittleView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addChild(myLittleView)
myLittleView.didMove(toParent: self)

myLittleView.view.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myLittleView.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

它没有像我预期的那样工作,因为小 View 没有出现在主视图上。有什么提示吗?

最佳答案

你不应该将框架布局与自动布局混合设置宽度和高度限制

NSLayoutConstraint.activate([
myLittleView.view.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myLittleView.view.centerYAnchor.constraint(equalTo: view.centerYAnchor),
myLittleView.view.heightAnchor.constraint(equalToConstant:100),
myLittleView.view.widthAnchor.constraint(equalToConstant:100)
])

myLittleView.view.frame = CGRect(x: 0, y: 0, width: 100, height: 100) 
myLittleView.view.center = view.center

override func loadView() {
view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}

编辑:

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
let myLittleView = MyLittleViewController()
myLittleView.willMove(toParent: self)
myLittleView.view.backgroundColor = .red
view.addSubview(myLittleView.view)
// enable auto-sizing (for example, if the device is rotated)
myLittleView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addChild(myLittleView)
myLittleView.didMove(toParent: self)
myLittleView.view.center = view.center
}
}

class MyLittleViewController: UIViewController {

override func loadView() {
view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}

}

关于ios - 如何在没有 Storyboard的情况下设置 ViewController 的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56856367/

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