[英]Custom UIView(.xib) changes frame automatically after adding as subview in UITableViewCell
[英]UITableViewCell has wrong height when adding custom view from xib as a subview
我有帶單元格的UITableView,我想在每個單元格中添加自定義視圖。 我創建了xib文件MyView.xib,並創建了類,該類是UIView類的擴展,並具有名稱MyView。 在xib文件中,我將File的Owner類添加為MyView。
在UITableViewCell中添加此自定義視圖時,我希望該自定義視圖具有動態高度。 這就是為什么我在init方法中添加此代碼的原因。
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
// 1. load the interface
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
// 2. add as subview
[self addSubview:self.view];
// 3. allow for autolayout
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
// 4. add constraints to span entire view
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
[self setStyle];
}
return self;
}
重要說明是我正在使用情節提要創建tableView。 因此,我具有帶有一個原型單元的表格視圖,並且在此處添加了具有其他內容的自定義視圖。 我正在使用自動布局。
現在的問題是,當我運行應用程序時,前幾個可見單元格的高度錯誤(自定義視圖不完全可見)。 當我向下滾動時,下一個單元格具有良好的高度(可見自定義視圖),而當我向下滾動時,列表頂部的少數單元格的高度是正確的。
有人可以告訴我第一次加載列表時如何解決單元格高度的問題嗎?
嘗試
- (void)awakeFromNib {
[super awakeFromNib];
// 1. load the interface
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
// 2. add as subview
[self addSubview:self.view];
// 3. allow for autolayout
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
// 4. add constraints to span entire view
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
[self setStyle];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.