Swift:无法将约束添加到ImageView

问题描述 投票:0回答:2

我正在使用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))
    }
}
ios swift constraints
2个回答
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)
}

0
投票

应该是:

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])
}
© www.soinside.com 2019 - 2024. All rights reserved.