gpt4 book ai didi

iphone - NSLayoutConstraints 代码使 View 居中并保持其纵横比

转载 作者:可可西里 更新时间:2023-11-01 03:37:30 24 4
gpt4 key购买 nike

我希望我的 subview 是一个以其父 View 顶部为中心的 16:9 矩形。换句话说,我希望它:

  1. 与其父 View 一样宽,但不超过 400 像素(UI 可以旋转为横向),
  2. 当它比父 View 窄时水平居中,
  3. 将其顶部固定到其父 View 的顶部,并且
  4. 更改其高度以保持 16:9 的纵横比。

这段代码几乎做到了,除了我很难使水平约束起作用并且没有超过或低于约束...

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

UIView *contentView = [[UIView alloc] init];
contentView.backgroundColor = [UIColor redColor];
[self.view addSubview:contentView];

contentView.translatesAutoresizingMaskIntoConstraints = NO;

NSDictionary *views = NSDictionaryOfVariableBindings(contentView);
NSMutableArray *constraints = [NSMutableArray array];

// this layout string is more like 'wishful coding'. I don't see why it wouldn't work
// but clearly this one is the problem
[constraints addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-(>=0)-[contentView(<=400)-(>=0)-]"
options:0 metrics:0 views:views]];

// this centering constraint below almost does the job, but doesn't give me a way
// to specify width, changing the one above to just @"H:[contentView(<=400)]"
// doesn't work either
[constraints addObject:
[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f]];

// 9:16 works fine, I think
[constraints addObject:
[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:contentView attribute:NSLayoutAttributeWidth
multiplier:9.0/16.0 constant:0.0]];

// pin the tops works fine, I think
[constraints addObjectsFromArray:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[contentView]"
options:0 metrics:0 views:views]];

[self.view addConstraints:constraints];
}

最佳答案

如果你想使红色框水平居中,那么你想等同于 View 的 CenterX,而不是 CenterY。因此该约束应如下所示:

[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f]];

然后在第一个约束上,你的约束是不明确的,因为有不止一种方法可以满足 >=0每边的边距和<=400在宽度上。更好的方法是准确地说出您在问题中所说的内容,即您需要宽度为 <=400 并且您希望边距为 0如果可能的话。

所以像这样:

[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0@900)-[contentView(<=400)]-(0@900)-|"
options:0 metrics:0 views:views]];

我相信这会得到您想要的?

关于iphone - NSLayoutConstraints 代码使 View 居中并保持其纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222789/

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