更新时间:2023-10-09 10:17:46
试试这个:
NSLayoutConstraint * xCenterConstraint = [NSLayoutConstraint constraintWithItem:厂景属性:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:视图2属性:NSLayoutAttributeCenterX乘数:1.0常数:0];
[上海华addConstraint:xCenterConstraint];NSLayoutConstraint * yCenterConstraint = [NSLayoutConstraint constraintWithItem:厂景属性:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:视图2属性:NSLayoutAttributeCenterY乘数:1.0常数:0];
[上海华addConstraint:yCenterConstraint];
更新了斯威夫特:
NSLayoutConstraint(项目:视图1,属性:.CenterX,relatedBy:.Equal,toItem:视图2,属性:.CenterX,事半功倍:1,恒:0)。主动=真NSLayoutConstraint(项目:视图1,属性:.CenterY,relatedBy:.Equal,toItem:视图2,属性:.CenterY,事半功倍:1,恒:0)。主动=真
In case of a successful Foursquare checkin, my iPhone app shows adds a view on top of the view which is shown.
I want the view to be centered on the X and Y and for it to have a definite width and height using autolayout, but I'm not sure which constraints to add programmatically. I know how to do it in Storyboard, but I'm not sure what exactly to type in code to do the same as this view is added later in response to a successful action in the app.
I can't get it working properly and the UIView has a nib which it loads with loadNibNamed:.
SuccessView *successfulCheckInView = [[SuccessView alloc] initWithFrame:CGRectZero];
successfulCheckInView.placeNameLabel.text = properVenue.name;
successfulCheckInView.placeAddressLabel.text = properVenue.address;
successfulCheckInView.delegate = self;
[self.ownerVC.view addSubview:successfulCheckInView];
Try this:
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];
Updated for Swift:
NSLayoutConstraint(item: view1, attribute: .CenterX, relatedBy: .Equal, toItem: view2, attribute: .CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: view1, attribute: .CenterY, relatedBy: .Equal, toItem: view2, attribute: .CenterY, multiplier: 1, constant: 0).active = true