gpt4 book ai didi

ios - 为什么我以编程方式创建的 View 会忽略其约束?

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

我有一个以编程方式创建 subview 并向其添加一些约束的 View 。由于某种原因,约束被完全忽略了。不会抛出任何错误。约束根本不会生效。 subview 与其父 View 具有相同的框架。我希望它是 400x400 并以其 super View 为中心。我在这里做错了什么?这是我在 super View 中的 initWithFrame:

- (id) initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
instructionsView = [[UIView alloc] initWithFrame:frame];
[self addSubview:instructionsView];
[self bringSubviewToFront:instructionsView];

[self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.
constant:0]];

[self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.
constant:0]];

[instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.
constant:400]];

[instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.
constant:400]];
}
return self;
}

我试过改变

instructionsView = [[UIView alloc] initWithFrame:frame];

instructionsView = [[UIView alloc] initWithFrame:CGRectZero];

没有成功。

最佳答案

您需要告诉 View 不要使用基于自动调整大小掩码的布局,而是使用自动布局

instructionsView.translatesAutoresizingMaskIntoConstraints = NO;

参见 documentation here

此外, View 应该在没有框架的情况下创建,这主要是一种样式,但是像这样创建 View :

instructionsView = [[UIView alloc] init];

关于ios - 为什么我以编程方式创建的 View 会忽略其约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687722/

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