gpt4 book ai didi

ios - View 不显示和自动布局集中

转载 作者:行者123 更新时间:2023-12-01 18:03:41 27 4
gpt4 key购买 nike

我想以编程方式在我的 View Controller 中添加一个 View 并集中它。我将 View 作为 subview 添加到父 View 并启用自动布局但它没有显示。

import UIKit

class ViewController: UIViewController {
lazy var newView:UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
return view
}()


let titleLable = UILabel()
let bodyLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(newView)
newView.translatesAutoresizingMaskIntoConstraints = false


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



}


}

最佳答案

试试这个方法

NSLayoutConstraint(item: newView,
attribute: NSLayoutConstraint.Attribute.centerX,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: view,
attribute: NSLayoutConstraint.Attribute.centerX,
multiplier: 1,
constant: 0).isActive = true

NSLayoutConstraint(item: newView,
attribute: NSLayoutConstraint.Attribute.centerY,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: view,
attribute: NSLayoutConstraint.Attribute.centerY,
multiplier: 1,
constant: 0).isActive = true

关于ios - View 不显示和自动布局集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61340858/

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