我正在使用ImageView在应用程序的菜单栏中添加一个UberLogo。但是,徽标被平移到单元格的左上角。我尝试使用在线视频将其重新定位到其包含的单元格中。 addConstraintWithFormat正在工作,但add Constraint无法工作。有人可以帮忙吗?谢谢!
class MenuCell: BaseCell {
let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "UberLogo")
return iv
}()
override func setupViews() {
super.setupViews()
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
addConstraintsWithFormat("H:|[v0(28)]|", views: imageView)
addConstraintsWithFormat("V:|[v0(28)]|", views: imageView)
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
}
您应在“约束”行之后致电addSubview(imageView)
您的setupViews
应该是这样->
override func setupViews() {
super.setupViews()
imageView.translatesAutoresizingMaskIntoConstraints = false
addConstraintsWithFormat("H:|[v0(28)]|", views: imageView)
addConstraintsWithFormat("V:|[v0(28)]|", views: imageView)
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
addSubview(imageView)
}
应该是:
override func setupViews() {
super.setupViews()
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
addConstraintsWithFormat("H:|[v0(28)]|", views: imageView)
addConstraintsWithFormat("V:|[v0(28)]|", views: imageView)
let centerConstraint = NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
imageView.addConstraints([centerConstraint, centerYConstraint])
}