我的故事板中有一個桌面視圖,其類設置爲我的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