Different Cell in Tableview Swift 3

Different Cell in TableView Swift 3

Assuming that you do know how to create your custom cell (if you don't check this question) 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
}

Swift UITableView Show Different Cell Every 10th Cell

There are two basic approaches:

  1. One (described by others) is to have your two arrays and have the UITableViewDataSource methods figure out which cell to dequeue based upon the indexPath.row % 10.

    The problem here, IMHO, is that you end up with ugly logic in your data source methods, mapping an indexPath.row to the appropriate row in your response array or ad arrays.

    So, I'd suggest utility functions, dataRow and adRow to reverse engineer what the index is in the associated array (returning nil if the IndexPath isn't relevant):

    extension ViewController: UITableViewDataSource {

    private func dataRow(for indexPath: IndexPath) -> Int? {
    let (quotient, remainder) = (indexPath.row + 1).quotientAndRemainder(dividingBy: adInterval)
    if remainder == 0 { return nil }
    return quotient * (adInterval - 1) + remainder - 1
    }

    private func adRow(for indexPath: IndexPath) -> Int? {
    let (quotient, remainder) = (indexPath.row + 1).quotientAndRemainder(dividingBy: adInterval)
    if remainder != 0 { return nil }
    return quotient - 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objects.count + ads.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let row = dataRow(for: indexPath) {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
    let object = objects[row]
    // configure cell using model data, `object`
    return cell
    } else if let row = adRow(for: indexPath) {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath)
    let ad = ads[row]
    // configure cell using ad data, `ad`
    return cell
    }

    fatalError("Did not find data or ad for cell: Should never get here")
    }

    }

    BTW, note that I'm not just doing indexPath.row % 10 (because I don't want the first thing shown to be an ad). So I'm actually doing (indexPath.row + 1) % 10.

  2. The other approach, is to have a single view model structure representative of the consolidated list of model objects and ads. For example, imagine I had model objects for items in my list and for ads:

    protocol Listable { }

    /// An Item is a model object for "real" objects to be shown in table

    struct Item: Listable {
    let string: String
    let imageURL: URL
    }

    /// An Ad is a model object for advertisement to be inserted into table

    struct Ad: Listable {
    let string: String
    }

    Then, given my list of items, I can then insert my ads, building a consolidated list of items and ads:

    var items: [Item]! = ...
    var list: [Listable]!

    override func viewDidLoad() {
    super.viewDidLoad()

    // build consolidated list of items and ads

    list = items
    for i in stride(from: adInterval, to: items.count, by: adInterval).reversed() {
    list.insert(Ad(...), at: i)
    }
    }

    Then the UITableViewDataSource methods don't have to do any math to figure out which array a particular listing is, but rather, just see which type it is and act accordingly:

    extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let listing = list[indexPath.row]

    if let item = listing as? Item {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
    // configure cell using `item`
    return cell
    } else if let ad = listing as? Ad {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath)
    // configure cell using `ad`
    return cell
    }

    fatalError("Did not find data or ad for cell: Should never get here")
    }

    }

which cell button has pressed in tableView in swift 3

  Here is update

just leave it, i explained it more simple,
create a button action in your cell class,then
Writre the code:-

> //Cell class

protocol CellDelegate: class {
func didTapCell(index: IndexPath)
}
var delegateCell:CellDelegate?
var indexPath:IndexPath?
@IBAction func buttonCellClick(_ sender: Any) {
delegateCell?.didTapCell(index: indexPath!)
}

> //In ViewController

cell.delegateCell = self
cell.indexPath = indexPath

func didTapCell(index: IndexPath) {
print("PRESS BUTTON >> \(index.row)")
}

UItableview on one click multiple cell are getting checked swift 3

Try this logic hope this will solve your problem

    let dict = [NSIndexPath: String]()

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

if let _ = // dict contains value at indexpath {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}

return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if ( // dict contains value == indexpath) {
// remove value from dict
} else {
//add value to dict
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}

Using different cell type in different sections of iOS table view

You may need to setup the heights of the cells.

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

How to return different views in UITableView Swift 3.0

Your idea is ok, you're using two different identifiers, but I also see that you just have 4 items in options array. Then inside cellForRowAt, you have

if indexPath.row <= 4 {

So it will never enter to the else. You'd need to change it to:

if indexPath.row < 3 {

Swift 3 - Rearrange and persist the cells in tableview

I managed to find a solution to my own question
I will post it here for future if anyone needed help

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let muscle = workout?.muscleList?[sourceIndexPath.row]
workout?.removeFromRawMuscles(at: sourceIndexPath.row)
workout?.insertIntoRawMuscles(muscle!, at: destinationIndexPath.row)

do{
try muscle?.managedObjectContext?.save()

}catch{
print("Rows could not be saved")
}
}


Related Topics



Leave a reply



Submit