我的故事板中有一个桌面视图,其类设置为我的UITableView
子类,名为SPSExplanationTableView
。在Interface Builder中,这个tableview没有设置约束。使用自动布局在桌面视图顶部定位视图
我想以编程方式创建UIView
显示在tableview中— which I know how to do(博客文章链接)的前—但其尺寸和使用自动布局定位。这是我的代码:
#import "SPSExplanationTableView.h"
@interface SPSExplanationTableView()
@property (nonatomic, strong) UIView *explanationView;
@end
@implementation SPSExplanationTableView
- (void)awakeFromNib
{
[super awakeFromNib];
self.explanationView = [[UIView alloc] init];
self.explanationView.translatesAutoresizingMaskIntoConstraints = NO;
self.explanationView.backgroundColor = [UIColor blueColor];
[self addSubview:self.explanationView];
[self bringSubviewToFront:self.explanationView];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f constant:150.0f];
[self.explanationView addConstraint:heightConstraint];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f constant:200.0f];
[self.explanationView addConstraint:widthConstraint];
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.0f constant:0.0f];
[self addConstraint:topConstraint];
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.0f constant:0.0f];
[self addConstraint:leftConstraint];
@end
当我运行它具有以下断言失败崩溃的应用程序:
*** Assertion failure in -[SPSExplanationTableView layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2935.137/UIView.m:8794 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. SPSExplanationTableView's implementation of -layoutSubviews needs to call super.'
以消息的字面和压倒一切的layoutSubviews
没有效果即我仍然得到同样的崩溃。
- (void)layoutSubviews
{
[super layoutSubviews];
}
什么是实现我想要实现的正确方法?
对于Aubada Taljo,这里是在Interface Builder中实现代码如下:
更新:我到底解决了这个自己不使用自动布局!我重写了我的SPSExplanationTableView类中的layoutSubviews方法,并将explainView的中心属性设置为自身边界的中心,稍微调整y轴位置以使其看起来如何。
谢谢,但我不知道如何在Interface Builder中的tableview上设置正确的约束,因为子视图在那里不存在。另外,我并不特别想用视图创建代码来混乱我的视图控制器。这感觉就像我应该能够使用一个自包含的tableview类。 – 2014-09-02 07:25:06
关键是您不必为子视图(someView)设置正确的约束,您只需在Interface Builder中为表视图设置正确的约束,上面的代码将完成剩下的工作。 此外,它不是很好的添加视图作为UITableView的一个孩子,因为它不是为此设计的,所以上面的代码会告诉你你想要什么 – 2014-09-02 09:34:40
那么tableview的正确约束是什么? – 2014-09-02 09:46:37