gpt4 book ai didi

ios - 为什么这个 UILabel 的水平位置不能用自动布局动态更新?

转载 作者:行者123 更新时间:2023-11-29 02:10:27 24 4
gpt4 key购买 nike

我有一个 UILabel socket ,它在 Storyboard中的 super View 顶部空间和 super View 的前导空间设置为 20。我想按一个按钮来动态更改约束以垂直和水平居中。垂直动态变化工作正常,但水平动态变化没有任何变化:

@IBAction func moveLabel(sender: AnyObject) {
self.view.addConstraint(NSLayoutConstraint(
item: self.label,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: 0))

self.view.addConstraint(NSLayoutConstraint(
item: self.label,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0))
}

水平间距保持在 20 领先于 superview,但垂直间距已正确应用以居中。为什么水平居中不起作用?

最佳答案

如果 Storyboard中已经有一个顶级约束,则需要停用该约束才能应用新约束并且不会发生崩溃。

您不应该在每次想要移动标签时都添加约束。您应该只在 viewDidLoad 甚至 Storyboard中添加一次约束,为它们创建 IBOutlets 并相应地激活/停用它们。

所以你的代码看起来像这样:

@IBOutlet weak var topOffsetConstraint : NSLayoutConstraint 
@IBOutlet weak var leadingOffsetConstraint : NSLayoutConstraint
@IBOutlet weak var horizontalCenterConstraint : NSLayoutConstraint
@IBOutlet weak var verticalOffsetConstraint : NSLayoutConstraint

@IBAction func moveLabel(sender: AnyObject) {
topOffsetConstranint.active = NO;
leadingOffsetConstraint.active = NO;
horizontalCenterConstraint.active = YES;
verticalOffsetConstraint.active = YES;

// If you don't need to animate the changes, remove the animation block
UIView.animateWithDuration(0.3) {
self.view.layoutIfNeeded();
}
}

我假设您想要来回移动标签。如果情况并非如此,并且您的 moveLabel 方法仅被调用一次,那么您的代码应该可以工作。只需确保停用 Storyboard中设置的约束并调用 layoutIfNeeded (也许在动画 block 中,如果这是您需要的)。

希望这对您的问题有所帮助!让我知道进展如何

关于ios - 为什么这个 UILabel 的水平位置不能用自动布局动态更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com