我正在TableViewCell
内的“配置文件视图控制器”上工作,并将表格单元格尺寸设置为UITableView.automaticDimension
:
问题是我想根据单元格宽度和16:9比率将背景图像视图(蓝色)设置为可变高度。由于某些原因,即使设置了常量,我也无法更改视图高度。
这里的代码:
let topView : UIView = {
let view = UIView()
view.translatesAutoresizingMaskintoConstraints = false
view.layer.cornerRadius = 20
view.backgroundColor = .yoofitDarkBlue
view.layer.masksToBounds = true
view.layer.shadowColor = UIColor.lightGray.cgColor
view.layer.borderWidth = 0.5
view.layer.borderColor = UIColor.yoofitDarkBlue.cgColor
view.layer.shadowOffset = CGSize(width: 0.0,height: 0.0)
view.layer.shadowRadius = 12.0
view.layer.shadowOpacity = 0.7
return view
}()
let userImage : UIImageView = {
let i = UIImageView()
i.translatesAutoresizingMaskintoConstraints = false
i.image = UIImage(named: "user2")
i.layer.masksToBounds = true
i.layer.cornerRadius = 75
i.layer.borderWidth = 1
i.layer.borderColor = UIColor.white.cgColor
return i
}()
var usernameLabel:UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskintoConstraints = false
l.font = UIFont(name: "AvenirNext-DemiBold",size: 20)
l.textAlignment = .center
l.textColor = .yoofitBlack
return l
}()
func setupViews() {
self.backgroundColor = .clear
self.selectionStyle = .none
addSubview(topView)
let width = self.frame.width
print(width) // print 320
topView.topAnchor.constraint(equalTo: topAnchor,constant: 10).isactive = true
topView.leftAnchor.constraint(equalTo: leftAnchor,constant: 8).isactive = true
topView.rightAnchor.constraint(equalTo: rightAnchor,constant: -8).isactive = true
topView.heightAnchor.constraint(equalToConstant: width/16*9).isactive = true // this doesn't work even if I set another number like 600
topView.layoutIfNeeded()
addSubview(userImage)
userImage.centerYAnchor.constraint(equalTo: topView.bottomAnchor).isactive = true
userImage.centerXAnchor.constraint(equalTo: topView.centerXAnchor).isactive = true
userImage.widthAnchor.constraint(equalToConstant: 150).isactive = true
userImage.heightAnchor.constraint(equalToConstant: 150).isactive = true
addSubview(usernameLabel)
usernameLabel.topAnchor.constraint(equalTo: userImage.bottomAnchor,constant: 10).isactive = true
usernameLabel.centerXAnchor.constraint(equalTo: userImage.centerXAnchor).isactive = true
usernameLabel.widthAnchor.constraint(equalToConstant: 200).isactive = true
usernameLabel.heightAnchor.constraint(equalToConstant: 20).isactive = true
usernameLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor,constant: -20).isactive = true
}