gpt4 book ai didi

ios - 在运行时更改自动布局

转载 作者:可可西里 更新时间:2023-11-01 04:28:47 25 4
gpt4 key购买 nike

是否可以在运行时更改自动布局约束?

我知道您可以更改常量,但您将如何更改不同的属性。

比如NSLayoutAttributeTop到NSLayoutAttributeBottom?

这是我希望实现的一个简单示例,它会在左上方设置一个标签,然后当您按下按钮时,它会在右下方设置标签。

初始约束按预期工作,点击按钮不会按预期工作并抛出臭名昭著的“无法同时满足约束”。

这是我使用的代码:

    - (void)viewDidLoad
{
[super viewDidLoad];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
self.constraintA = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0];

self.constraintB = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0];

[self.view addConstraint:self.constraintA];
[self.view addConstraint:self.constraintB];
}

- (IBAction)tappedChange:(id)sender
{

[self.view removeConstraints:@[ self.constraintA, self.constraintB ]];

self.constraintA = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];

self.constraintB = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0];
[self.view addConstraint:self.constraintA];
[self.view addConstraint:self.constraintB];
[self.view setNeedsLayout];
}

感谢您的宝贵时间。

最佳答案

您只需要在 iOS 7 及以下版本上执行删除/重新创建/添加约束舞蹈。如果您正在为现代 iOS(8 及更高版本)编写代码,您可以一次创建所有约束,然后只需在您想要的任何 NSLayoutConstraint 实例上设置 .active 属性任何给定时间。

// Move to right
self.leadingConstraint.active = false;
self.trailingConstraint.active = true;

// Move to bottom
self.topConstraint.active = false;
self.bottomConstraint.active = true;

如果您使用的是 Interface Builder,您可以创建所有所需的约束(请注意默认情况下未激活的灰色约束)。

Xcode Window Showing Example

然后当按下按钮时,您可以停用旧约束并激活新约束。

如果您不确定所显示的 View ,您可以暂停应用程序执行并在调试器中使用以下私有(private) API 打印出完整的 View 和约束列表:

po [[UIWindow keyWindow] _autolayoutTrace]

关于ios - 在运行时更改自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33682893/

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