Thanh Hải Thanh Hải - 1 month ago 9
Swift Question

Different Cell in TableView Swift 3

As a beginner, I'm trying to work with

UITableView
and
IOCollectionView
, How can I create different cells (some cells have a collection View and some cells have text or image only,...) in the same container?

For example: the Appstore, the cell on the top is a banner, containing wide Collection View, second cell containing a category a the others containing label or button.

I work with swift 3 and prefer to use storyboard.

Answer

Assuming that you do know how to create your custom cell (if you don't check this answer) and implementing the required data source methods, you should do this in cellForRowAt or cellForItem methods -I'm using cellForRowAt in the code snippet-:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // first row should display a banner:
        if indexPath.row == 0 {
            let bannerCell = tableView.dequeueReusableCell(withIdentifier: "BannerTableViewCell") as! BannerTableViewCell

            // ...

            return bannerCell
        }

        // second row should display categories
        if indexPath.row == 1 {
            let categoriesCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! CategoriesTableViewCell

            // ...

            return categoriesCell
        }

        // the other cells should contains title and subtitle:
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! TileAndSubtitleTableViewCell

        // ...

        return defaultCell
    }

Make it more readable:

you can also define enum for checking the indexPath.row instead of compare them to ints:

enum MyRows: Int {
    case banner = 0
    case categories
}

Now, you can compare with readable values:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // first row should display a banner:
        if indexPath.row == MyRows.banner.rawValue {
            let bannerCell = tableView.dequeueReusableCell(withIdentifier: "BannerTableViewCell") as! BannerTableViewCell

            // ...

            return bannerCell
        }

        // second row should display categories
        if indexPath.row == MyRows.categories.rawValue {
            let categoriesCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! CategoriesTableViewCell

            // ...

            return categoriesCell
        }

        // the other cells should contains title and subtitle:
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! TileAndSubtitleTableViewCell

        // ...

        return defaultCell
    }

Hope that helped.

Comments