gpt4 book ai didi

ios - 尝试以编程方式实现约束时约束被忽略

转载 作者:行者123 更新时间:2023-11-28 06:16:53 25 4
gpt4 key购买 nike

我试图通过设置约束使 logoImage 水平和垂直居中,但在测试时,它显示在 (x:0, y:0) 上。知道如何解决这个问题吗?谢谢

var movieView : UIView?
let logoImage = UIImageView(image: #imageLiteral(resourceName: "my_logo"))

// This function runs in viewWillAppear
internal func setupIntroMovie() {
movieView = UIView(frame: view.frame)
view.addSubview(movieView!)
view.addSubview(logoImage)

let horizontalConstraint = NSLayoutConstraint(item: logoImage,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant: 0)
let verticalConstraint = NSLayoutConstraint(item: logoImage,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1,
constant: 0)
view.addConstraints([horizontalConstraint,
verticalConstraint])
updateViewConstraints()
}

最佳答案

您需要设置 logoImage.translatesAutoresizingMaskIntoConstraints = false,因为它确定 View 的自动调整掩码是否转换为自动布局约束。

internal func setupIntroMovie() {
movieView = UIView(frame: view.frame)
view.addSubview(movieView!)
view.addSubview(logoImage)

let horizontalConstraint = NSLayoutConstraint(item: logoImage,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant: 0)
let verticalConstraint = NSLayoutConstraint(item: logoImage,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1,
constant: 0)
// Update
logoImage.translatesAutoresizingMaskIntoConstraints = false

view.addConstraints([horizontalConstraint,
verticalConstraint])
updateViewConstraints()
}

If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame , bounds , or center properties, allowing you to create a static, frame-based layout within Auto Layout.

关于ios - 尝试以编程方式实现约束时约束被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44868459/

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