在应用logoView(定位和缩放)和titleLabel约束后,NSLayoutConstraint
和.scaleAspectFill
出现问题,titleLabel的Y位置未正确设置
titleLabel.topAnchor.constraint(equalTo:logoView.bottomAnchor, 常数:20])
这里是我的样本:
let logoView:UIImageView = {
let img = UIImage(named: "big_logo")
let im = UIImageView(image: img)
im.translatesAutoresizingMaskIntoConstraints = false
im.contentMode = .scaleAspectFill
return im
}()
lazy var titleLabel:UILabel = {
let title:UILabel = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.text = MuiPack.getMuiString(key: "splash_greeting")
title.font = UIFont.boldSystemFont(ofSize: 18)
title.textColor = .black
return title
}()
NSLayoutConstraint.activate([logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20)])
NSLayoutConstraint.activate([titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
titleLabel.topAnchor.constraint(equalTo: logoView.bottomAnchor, constant: 20])
答案 0 :(得分:1)
您的logoView
没有intrinsicSize,因此没有高度。
如果按如下方式更改初始化,您将看到发生了什么:
let logoView:UIImageView = {
let img = UIImage(named: "cross")
let im = UIImageView(image: img)
im.translatesAutoresizingMaskIntoConstraints = false
im.contentMode = .scaleAspectFill
// set a background color so you can see the image view's frame
im.backgroundColor = .blue
// clip the image to the bounds of the view's frame
im.clipsToBounds = true
return im
}()
您可以设置显式高度约束,也可以将其设置为与宽度成比例。
这将使其成为“方形”:
NSLayoutConstraint.activate([
logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20),
// add proportional height anchor
logoView.heightAnchor.constraint(equalTo: logoView.widthAnchor, multiplier: 1.0)
])