使用Autolayout约束在父视图中居中视图

时间:2016-04-25 22:59:30

标签: ios

我有一个类型为UIView的self.photoView,我有一个UImageView的photoImageView。我想将photoImageView X和Y置于self.photoView中心。

此代码没有做任何事情!

let photoImageView = UIImageView.imageViewForPhotoTaken(self.photoView.bounds, image: img)
            photoImageView.contentMode = UIViewContentMode.ScaleAspectFit

            self.photoView.addSubview(photoImageView)

            // set the autolayout constraints 
            self.photoView.addConstraint(NSLayoutConstraint(item: self.photoView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: photoImageView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))

2 个答案:

答案 0 :(得分:0)

在添加约束之前,您需要在translatesAutoresizingMasksIntoConstraints = falsephotoView上致电photoImageView

答案 1 :(得分:0)

试试这段代码:

let photoImageView = UIImageView(image:UIImage(named: "logo"))
photoImageView.contentMode = UIViewContentMode.ScaleAspectFit
self.photoView.addSubview(photoImageView)
photoImageView.translatesAutoresizingMaskIntoConstraints = false

// set the autolayout constraints
self.photoView.addConstraint(NSLayoutConstraint(item: photoImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.photoView, attribute: .CenterX, multiplier: 1, constant: 0))
self.photoView.addConstraint(NSLayoutConstraint(item: photoImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self.photoView, attribute: .CenterY, multiplier: 1, constant: 0))

如果你想要水平和垂直中心,你应该设置'中心X'和'中心Y'约束

另外,请确保在设置此

之前为'self.photoView'设置了适当的约束

你应该把这段代码放在'viewDidAppear'或者在此之后调用的任何方法