【问题标题】:Constraints to replace frame for UIButton替换 UIButton 框架的约束
【发布时间】:2024-01-07 23:00:01
【问题描述】:

我正在尝试用 UIButton 的约束替换设置的框架,但我的代码不断崩溃,我做错了什么?

- (void)CreateButton {
self.Button = [[UIButton alloc] init];
//self.Button.frame = CGRectMake(30, 30, 100, 100);
[self.Button addConstraint:[NSLayoutConstraint constraintWithItem:MyScrollView
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.myButton
                                                          attribute:NSLayoutAttributeTop
                                                         multiplier:2.0
                                                           constant:30]];
[self.myButton addConstraint:[NSLayoutConstraint constraintWithItem:MyScrollView
                                                          attribute:NSLayoutAttributeHeight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.myButton
                                                          attribute:NSLayoutAttributeHeight
                                                         multiplier:3.0
                                                           constant:50]];
[self.myButton setBackgroundColor:[UIColor orangeColor]];
[self.myButton setTitle:@"Press Me" forState:UIControlStateNormal];
[self.myButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[MyScrollView addSubview:self.myButton];

【问题讨论】:

  • “崩溃”,嗯?如果您向我们显示错误消息告诉我们导致崩溃的代码的确切行,我们可能会提供更多帮助。
  • 假设您想为单个按钮设置约束,至少您在上面的代码中有两个不同的(self.Button 和 self.myButton)
  • 并为了 Universe 的简单性而尝试坚持 obj-C 命名约定。这将帮助您避免将来出现此类问题developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…
  • 在添加约束之前,您还需要将 UIButton 添加到您的滚动视图中
  • 而且,在添加约束之前你必须写:self.myButton.view.translatesAutoresizingMaskIntoConstraints = NO;

标签: objective-c uibutton constraints frame nslayoutconstraint


【解决方案1】:

您应该将约束添加到 MyScrollView。

【讨论】:

  • 这不会导致崩溃。
  • 来自 UIView 的文档:addConstraint:“约束必须只涉及接收视图范围内的视图。具体来说,涉及的任何视图必须是接收视图本身,或者是接收视图。添加到视图的约束被称为由该视图持有。评估约束时使用的坐标系是持有约束的视图的坐标系。"