簡體   English   中英

UICollectionViewCell里面的UITableView

[英]UITableView inside UICollectionViewCell

我想在UICollectionViewCell中包含UITableView。 然后,我將通過UICollectionViewCell的子類動態更改UITableView的內容。

我的UICollectionViewCell .h子類如下所示:

@interface ShopCollectionCell : UICollectionViewCell <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) IBOutlet UILabel *myLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

在.m中只是標准的UITableView方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bla"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bla"];
    }

    cell.textLabel.text = @"test";
    return cell;
}

在我的UIViewController中,我有一個UICollectionView,在其中執行以下操作:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopCollectionCell *cell = (ShopCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopDetailCell" forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[ShopCollectionCell alloc] init];//:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.myLabel.text = @"test";

    return cell;
}

我不明白為什么我會得到僵屍對象?

在此處輸入圖片說明

為了能夠使用dequeueReusableCellWithReuseIdentifier:forIndexPath您還需要為該單元格標識符注冊一個類或一個筆尖。

在viewDidLoad中,您應該使用下面的兩個UITableView方法之一來注冊一個單元格

registerNib:forCellReuseIdentifier:
registerClass:forCellReuseIdentifier:

查看UITableView文檔以獲取有關如何使用它們的更多詳細信息

然后,您應該可以完全刪除以下幾行:

   if (cell == nil) {
        cell = [[ShopCollectionCell alloc] init];//:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

更新:您發布給我的錯誤消息使您很容易找出問題所在。 您以擁有者“ self”的身份加載了NIB,然后用從NIB加載的第一個視圖替換了self。 我將UIView用作NIB中的rootview,並將該加載的視圖添加到單元格的contentView屬性中。

嘗試刪除集合視圖單元格的alloc和init。 dequeueReusableCellWithReuseIdentifier是足夠的。 從蘋果文檔:

如果有一個可用的單元格,此方法將使該單元出隊,或者根據您先前注冊的類或nib文件創建一個新的單元格。

進行以下3項更改對我有用。

  1. 在ShopCollCell.xib中,將tableView委托和數據源映射到ShopCollectionCell類而不是File的所有者。

  2. 在ShopCollectionCell.m中實現initWithCoder:方法。

  3. 在ShopCollectionCell.m中,實現awakeFromNib方法並在此處為mytableView注冊UITableViewCell類。

     - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:aDecoder]) { } return self; } - (void)awakeFromNib { [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"bla"]; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM