2016-04-25 67 views
0

我有一个self.photoView,它是UIView类型的,我有photoImageView,它是UIImageView。我想将photoImageView X和Y置于self.photoView中。使用Autolay约束在父视图中居中视图

此代码没有做任何事情!

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)) 
+0

调用的任何方法,我要对齐的子VI ew(photoImageView)中心水平和中心垂直。 –

+0

您需要为这两个轴创建一个约束,并且很可能您还应该声明高度和宽度约束......您的代码不表示UIImageView应该是除0以外的任何大小 – Loxx

+0

解决了您的问题? – HardikDG

回答

0

你需要调用translatesAutoresizingMasksIntoConstraints = falsephotoViewphotoImageView哟添加约束之前。

+0

我试过了,但没有奏效。 –

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”或者是在此之后