gpt4 book ai didi

ios - 需要帮助使用自动布局在中心设置 UIButton

转载 作者:行者123 更新时间:2023-11-28 21:32:49 25 4
gpt4 key购买 nike

我正在尝试使用 AutoLayouts 以编程方式在中心垂直和水平设置 UIButton 这是我的代码:

- (void)awakeFromNib {
UIView *av = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 35.0)];

UIButton *doneButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 37, 30)];

//UIButton title, color, backgroung color, targer action ...

NSLayoutConstraint* cn3 = [NSLayoutConstraint constraintWithItem:doneButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:av
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[av addConstraint:cn3];

NSLayoutConstraint* cn4 = [NSLayoutConstraint constraintWithItem:doneButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:av
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[av addConstraint:cn4];

[av addSubview:doneButton];
self.theTextField.inputAccessoryView = av;
}

除了一件事,上面的代码工作正常,我在控制台中收到此警告:

The view hierarchy is not prepared for the constraint: NSLayoutConstraint:0x7fcfc494efb0 UIButton:0x7fcfc2624420'Done'.centerX == UIView:0x7fcfc2624230.centerX

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.

并且对 Y 得到相同的警告。

请告诉我出现此警告的原因是什么?

最佳答案

设置约束之前,将 doneButton 添加到 av View 。

[av addSubview:doneButton];

[av addConstraint:cn3];
[av addConstraint:cn4];

关于ios - 需要帮助使用自动布局在中心设置 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227281/

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