以编程方式使用Autolayout Constraints将UIImageView置于UIView Swift 2.3 iOS10中

时间:2016-11-05 22:50:21

标签: ios swift autolayout

我通过故事板在表格单元格中添加了一个UIView,其中包含以下约束:

enter image description here

然后我有以下代码以编程方式将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!)

但是,在横向拍摄时,我的图像不会居中。我的图像只是屏幕宽度的一半,我想把它放在我的UIView中。我错过了什么?感谢

2 个答案:

答案 0 :(得分:5)

  1. 对于imageView的宽度和高度,您应该使用自动布局而不是框架
  2. 您必须在添加约束
  3. 之前将imageView添加到imageWrapperView
  4. 您必须将imageView.translatesAutoresizingMaskIntoConstraints设置为false
  5. 然后,最终的代码是:

        //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])
    

答案 1 :(得分:0)

当您使用自动布局时,请勿尝试更改视图的框架。如果您需要更改框架,最好采用约束的出口并以编程方式更改它们。

在您的问题中,要将imageView居中对齐,您可以通过放置4个约束来实现。设置imageView的高度和宽度,另外两个是水平居中和垂直居中约束。

这是居中对齐任何类型视图的基本方法。