静态TableViewCell里面的UICollectionView

cyr*_*ril 2 uitableview ios uicollectionview swift

我在网上看到很多关于在动态表视图单元格中嵌入UICollectionViews的教程,并对集合视图进行子类化以设置委托,但我想知道静态表格视图单元格的过程是否有所不同.

我试着按照这里的例子,但我不能完全遵循它,因为它似乎过于复杂,几乎没有解释.有人会介意我需要完成的基本步骤,以使我的集合视图工作吗?

到目前为止,这是我的代码:

class FeaturedController: UITableViewController, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    popularCollectionView.dataSource = self
    popularCollectionView.delegate = self
}

//MARK: Popular Events Collection View
    @IBOutlet weak var popularCollectionView: UICollectionView!

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = popularCollectionView.dequeueReusableCellWithReuseIdentifier("popular", forIndexPath: indexPath) as! UICollectionViewCell

        return cell
    }
Run Code Online (Sandbox Code Playgroud)

非常感谢!

yus*_*024 6

如果您知道如何将集合视图添加到动态表视图单元格,则将其添加到静态表单单元格中会更容易.你根本不需要任何子类(但这样做可能是一个好主意).在引擎盖下,静态表视图只不过是一个普通的表视图,它可以从主机支持UITableViewController自动设置Interface Builder中的布局.那么,这是如何做到的:

  1. 从Interface Builder中的对象库拖动集合视图并将其放在所需的单元格中.
  2. 确保表视图由表视图控制器托管.
  3. 在单元格中设置约束或布局集合视图.
  4. 将Collection View的dataSource设置为托管的Table View Controller.
  5. 添加UICollectionViewDataSource表视图控制器的一致性.
  6. 实现UICollectionViewDataSource的方法,即collectionView:numberOfItemsInSection:collectionView:cellForItemAtIndexPath:UITableViewController.

如果你知道如何使用UITableViewUICollectionView一般,这应该不难遵循.

更新 您的代码看起来应该有效.所以,你应该检查是否:

  1. 您确实已将Table View Controller的类设置为您的FeaturedController类.
  2. 您确实已将Interface Builder中的Collection View连接到popularCollectionView.
  3. 您已经拥有带有标识符的原型Collection View Cell popular.虽然,如果你没有这样做,它应该会崩溃.
  4. 在IB中,您已将表视图设置为静态.

我在这里做了一个小例子

Interface Builder

橙色视图是集合视图,带有绿色视图,原型集合视图单元格带有标识符myCell.

数据源

然后我将视图控制器设置为Collection View的数据源.但你也可以在代码中设置它,就像你一样.

然后我实现下面的数据源方法.

@interface ViewController () <UICollectionViewDataSource>

@end

@implementation ViewController

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 20;
}

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

@end
Run Code Online (Sandbox Code Playgroud)

这就是结果:

结果