gpt4 book ai didi

ios - 无法让从 UIView() 子类化的对象在其父 View 中正确定位

转载 作者:行者123 更新时间:2023-11-29 06:02:26 25 4
gpt4 key购买 nike

我试图在其父 View squareParentView 中放置一个 UISquare() 对象 square。当我尝试使用自动布局来实现此目的时,我惨遭失败。

这是我的UISquare类供引用:

class UISquare: UIView() {

override init(frame: CGRect) {
super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func draw(_ rect: CGRect) {
//.. setup the square. Implementation details are not relevant to this question ..
}
}

这是我的ViewController类:

class viewController: UIViewController {

let square = UISquare(x: 100, y: 100, width: 100, height: 100)

let squareParentView = UIView()


override func viewDidLoad() {
super.viewDidLoad()


view.addSubview(squareParentView)
squareParentView.translatesAutoresizingMaskIntoConstraints = false

// Here I am simply making squareParentView the same size as self.view
squareParentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
squareParentView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
squareParentView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
squareParentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

// Here I am setting up the square and enabling auto layout
squareParentView.addSubview(square)
square.translatesAutoresizingMaskIntoConstraints = false

// PROBLEM AREA RIGHT HERE
square.centerXAnchor.constraint(equalTo: squareParentView.centerXAnchor).isActive = true
square.centerYAnchor.constraint(equalTo: squareParentView.centerYAnchor).isActive = true

}
}

当我执行代码时,正方形没有出现在屏幕上。就像它完全忽略了自动布局和我的指示,使其中心位于其父 View 的中心。

如果我去掉设置正方形约束的行(即,如果我根本不使用自动布局),则正方形将按预期出现在 squareParentView 的左上角。

我怀疑这不起作用的原因是因为当你处理UIViews(例如UISquare)时,仅仅改变布局约束是不够的,而是改变UIView的框架应该设置到所需的位置(即在我的例子中,设置 square.center = squareParentView.center )。然而,当我设置它时,没有观察到任何差异。无论如何,我不想将自动布局与代码库中的框架混合在一起,所以我想知道是否有办法使用自动布局独占在其父 View 中居中这个正方形.


我还有一个后续问题:

我的代码中的打印语句揭示了一些相当奇怪的东西:

print(squareParentView.center)        // prints (0,0)

当我以编程方式设置父 View 的约束以使其填充 self.view 时,为什么我的父 View 的中心设置为 (0,0)?

squareParentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
squareParentView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
squareParentView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
squareParentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

什么给出了?

最佳答案

将这两行添加到代码中:

 square.widthAnchor.constraint(equalToConstant: 100).isActive = true
square.heightAnchor.constraint(equalToConstant: 100).isActive = true

关于ios - 无法让从 UIView() 子类化的对象在其父 View 中正确定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54491317/

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