How can I center a UIView programmatically on top of an existing UIView using Autolayout?(如何使用 Autolayout 以编程方式将 UIView 居中在现有 UIView 之上?)
问题描述
如果 Foursquare 签入成功,我的 iPhone 应用会在显示的视图之上添加一个视图.
In case of a successful Foursquare checkin, my iPhone app shows adds a view on top of the view which is shown.
我希望视图以 X 和 Y 为中心,并使用自动布局使其具有确定的宽度和高度,但我不确定以编程方式添加哪些约束.我知道如何在 Storyboard 中执行此操作,但我不确定要输入什么代码才能执行相同的操作,因为稍后会添加此视图以响应应用程序中的成功操作.
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.
我无法让它正常工作,并且 UIView 有一个用 loadNibNamed: 加载的 nib.
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];
推荐答案
试试这个:
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 更新:
Updated for 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
这篇关于如何使用 Autolayout 以编程方式将 UIView 居中在现有 UIView 之上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Autolayout 以编程方式将 UIView 居中在现有 UIView 之上?


基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01