gpt4 book ai didi

iphone - 为什么约束不适用于 UIView 但适用于 UILabel?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:58:47 25 4
gpt4 key购买 nike

我这里有一个简单(完整)的例子,看起来很奇怪,但我肯定只是漏掉了一些小东西……对吧?你能帮忙调试下面的简单代码吗?此代码使 aView 消失,但是当我将 aLabel 放在 aView 所在的约束中时,它会完美运行。为什么?感谢您的任何意见,这对我来说似乎很疯狂。

奥斯汀

UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 30)];
aView.backgroundColor = [UIColor redColor];
aView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:aView];

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 30)];
aLabel.backgroundColor = [UIColor redColor];
aLabel.text = @"Label";
aLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:aLabel];

NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:aView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];

[self.view addConstraint:myConstraint];

myConstraint =[NSLayoutConstraint
constraintWithItem:aView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];

[self.view addConstraint:myConstraint];

最佳答案

好吧,行 aView.translatesAutoresizingMaskIntoConstraints = NO;正在使 View 的大小为零。所以你必须添加这些代码行:

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100];
[aView addConstraint:widthConstraint];


NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
[aView addConstraint:heightConstraint];

关于iphone - 为什么约束不适用于 UIView 但适用于 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094879/

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