以编程方式使用自动布局约束将UIImageView置于UIView Swift 2.3 iOS10内部

Jac*_*ace 2 ios autolayout swift

我已通过我的情节提要向表单元格添加了一个UIView,并具有以下约束:

在此处输入图片说明

然后,我得到以下代码,以编程方式将UIImageView添加到上述UIView并根据屏幕方向调整其大小。

            //Use half the screen size width when on an iPhone and on Landscape
            let image: UIImage = UIImage(named: HEADER_IMAGE_BATH)!
            imageView = UIImageView(image: image)
            imageView!.frame = CGRectMake(0 , 0, self.view.frame.width / 2, 185)
            imageView!.contentMode = .ScaleAspectFit
            //center image
            let centerXConst = NSLayoutConstraint(item: imageView!, attribute: .CenterX, relatedBy: .Equal, toItem: imageWrapperView, attribute: .CenterX, multiplier: 1, constant: 1)
            let centerYConst = NSLayoutConstraint(item: imageView!, attribute: .CenterY, relatedBy: .Equal, toItem: imageWrapperView, attribute: .CenterY, multiplier: 1, constant: 1)
            NSLayoutConstraint.activateConstraints([centerXConst, centerYConst])
            //add to sub view
            imageWrapperView.addSubview(imageView!)
Run Code Online (Sandbox Code Playgroud)

但是,风景时我的图像不会居中。我的图像仅是屏幕宽度的一半,我想将其居中放置在UIView中。我想念什么?谢谢

Dan*_*ynh 7

  1. 对于imageView的宽度和高度,您应该使用自动版式而不是框架
  2. 您必须在添加约束之前将imageView添加到imageWrapperView
  3. 您必须将imageView.translatesAutoresizingMaskIntoConstraints设置为false

然后,最终代码为:

    //Use half the screen size width when on an iPhone and on Landscape
    let image: UIImage = UIImage(named: "key.png")!
    let imageView = UIImageView(image: image)
    imageView.contentMode = .ScaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    //add to sub view
    imageWrapperView.addSubview(imageView)

    //center image
    let centerXConst = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: imageWrapperView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
    let centerYConst = NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: imageWrapperView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)

    let heightConstraint = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 185.0)
    let widthConstraint = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: self.view.frame.width / 2)
    imageView.addConstraints([heightConstraint, widthConstraint])

    NSLayoutConstraint.activateConstraints([centerXConst, centerYConst])
Run Code Online (Sandbox Code Playgroud)