【发布时间】:2018-08-28 16:22:56
【问题描述】:
我正在尝试在三个按钮下做一条简单的线来创建标签效果。虽然我可以在 Storyboard 中执行此操作,但我想在代码中执行此操作,并且理想情况下使该行成为视图中已有元素的子视图,以避免必须对其进行特殊约束。
我的方法是创建一个没有文本和背景颜色的 UILabel。我可以使 UILabel 成为 View 的子视图,但是,它不会将其附加到按钮的底部。
另一方面,如果我将 UILabel 设为其中一个按钮的子视图,我将看不到它。
谁能提出一个简单的方法来做到这一点?
[centerButton setTitle:@"Favorites" forState:UIControlStateNormal];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 120, 280, 2)];
label.backgroundColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 1;
label.text = @"";
[self.view addSubview: label];
提前感谢您的任何建议。
编辑:
我尝试以编程方式添加一些 NSLayoutConstraints:
NSLayoutConstraint *con3 = [NSLayoutConstraint
constraintWithItem:label attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual toItem:centerButton
attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
[label addConstraints:@[con3]];
//tried with and without
[self.view layoutIfNeeded];
这返回了异常:
[LayoutConstraints] The view hierarchy is not prepared
for the constraint: <NSLayoutConstraint:0x174e85500 V:
[UIButton:0x100b0baf0'Now']-(0)-[UILabel:0x108555160]
(inactive)>
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.
在故事板中创建的按钮是 self.view 的子视图,我将标签添加到 self.view 作为代码中的子视图,因此不确定为什么会发生异常。
【问题讨论】:
-
对于这种事情,框架数学在这一点上是相当老派的。我肯定会尝试约束。
-
视图非常复杂,有很多故事板自动布局约束。只是希望将线分配给已经受到约束的东西,以免重做很多现有的约束
-
您想要从一个“标签按钮”到选定的“动画”行吗?还是您只想显示一条线?
-
或者,您可以尝试
UISegmentedControl子类并调整其外观。它会处理布局本身。 -
使用约束会更容易实现你想要做的事情。
标签: ios objective-c line