Iphone 如何使用Autolayout以编程方式将UIView居中于现有UIView之上?

Iphone 如何使用Autolayout以编程方式将UIView居中于现有UIView之上?,iphone,ios,uiview,autolayout,Iphone,Ios,Uiview,Autolayout,如果Foursquare签入成功,我的iPhone应用程序shows会在显示的视图顶部添加一个视图 我希望视图以X和Y为中心,并使用autolayout使其具有一定的宽度和高度,但我不确定以编程方式添加哪些约束。我知道如何在Storyboard中实现这一点,但我不确定到底要键入什么代码来实现这一点,因为该视图将在稍后添加,以响应应用程序中的成功操作 我无法使其正常工作,UIView有一个nib,它使用LoadNibName:加载该nib SuccessView *successfulCheckI

如果Foursquare签入成功,我的iPhone应用程序shows会在显示的视图顶部添加一个视图

我希望视图以X和Y为中心,并使用autolayout使其具有一定的宽度和高度,但我不确定以编程方式添加哪些约束。我知道如何在Storyboard中实现这一点,但我不确定到底要键入什么代码来实现这一点,因为该视图将在稍后添加,以响应应用程序中的成功操作

我无法使其正常工作,UIView有一个nib,它使用LoadNibName:加载该nib

SuccessView *successfulCheckInView = [[SuccessView alloc] initWithFrame:CGRectZero];
successfulCheckInView.placeNameLabel.text = properVenue.name;
successfulCheckInView.placeAddressLabel.text = properVenue.address;
successfulCheckInView.delegate = self;

[self.ownerVC.view addSubview:successfulCheckInView];
试试这个:

NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[superview addConstraint:xCenterConstraint];

NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[superview addConstraint:yCenterConstraint];
为Swift更新:

NSLayoutConstraint(item: view1, attribute: .centerX, relatedBy: .equal, toItem: view2, attribute: .centerX, multiplier: 1, constant: 0).isActive = true

NSLayoutConstraint(item: view1, attribute: .centerY, relatedBy: .equal, toItem: view2, attribute: .centerY, multiplier: 1, constant: 0).isActive = true

你到底不知道怎么做?您是否尝试过使用constraintWithItem:attribute:relatedBy:toItem:attribute:乘数:常数:?view1和view2是什么?如果只是对齐视图的中心,关系的顺序并不重要<代码>视图1和
视图2
只是您正在对齐的不同视图。如果顺序无关紧要,我们如何确保视图1重新定位为与视图2居中,而不是相反?这取决于视图的位置。例如,如果view1定义了顶部和前导约束,而view2没有其他约束,则view2会“移动”。但是,如果两者都有冲突的约束,则约束优先级可能会更复杂,等等。我鼓励您在故事板中玩一玩,看看在不同情况下是如何工作的!不要忘记哦,很容易忘记的视图1.translates自动调整大小gmaskintoconstraints=false