【问题标题】:How can I center a UIView programmatically on top of an existing UIView using Autolayout?如何使用 Autolayout 以编程方式将 UIView 居中在现有 UIView 之上?
【发布时间】:2013-09-01 00:35:47
【问题描述】:

如果 Foursquare 签入成功,我的 iPhone 应用会在显示的视图之上添加一个视图。

我希望视图以 X 和 Y 为中心,并使用自动布局使其具有确定的宽度和高度,但我不确定以编程方式添加哪些约束。我知道如何在 Storyboard 中执行此操作,但我不确定要输入什么代码才能执行相同的操作,因为稍后会添加此视图以响应应用程序中的成功操作。

我无法让它正常工作,并且 UIView 有一个用 loadNibNamed: 加载的 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];

【问题讨论】:

  • 你不知道该怎么做?您是否尝试过使用 constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:?

标签: iphone ios uiview autolayout


【解决方案1】:

试试这个:

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

【讨论】:

  • view1 和 view2 是什么?
  • 在我们只是对齐视图中心的情况下,关系的顺序无关紧要。 view1view2 只是您要对齐的不同视图。
  • 如果订单无关紧要,我们如何确保例如view1 重新定位为 view2 的中心而不是相反?
  • 这取决于视图的位置。例如,如果 view1 定义了顶部和前导约束,而 view2 没有其他约束,则 view2 将“移动”。但是,如果它们都有相互冲突的约束,那么约束优先级等情况可能会更加复杂。我鼓励您只是在故事板中玩耍,看看事情在不同情况下是如何工作的!
  • 别忘了哦 太容易忘记了 view1.translatesAutoresizingMaskIntoConstraints = false
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
相关资源
最近更新 更多