قالب وردپرس درنا توس
Home / IOS Development / ios – Swift table view different views

ios – Swift table view different views



I have a UITableView with many different kinds of views. In each method in the UITableView data source, I have to check the type of cell and type of the object, throw it and function properly. This is not very clean (it works) but not very serviceable.

So I worked on something to abstract this part, but I'm a little bit stuck. The following code is simplified and may not be useful, but it is to demonstrate my current problem:

  extension UITableView {
func dequeue  (_ type: T.Type,
for indexPath: IndexPath) -> T {
la cell = dequeueReusableCell (withIdentifier: String (describes: type),
for: indexPath)
guard let cellT = cell like? T else {
fatalError ("Dequeue failed, expect: (type) was: (cell)")
}

return cellT
}
}

struct row  {
let display: Cell.Type
let model: model

was fill: ((model, cell) -> invalid)
}

// Completely unrelated models
struct person {
let the name: String
}

struct Animal {
leave age: Int
}

// Completely unrelated views
class PersonView: UITableViewCell {

}

class AnimalView: UITableViewCell {

}


// Use:
la person = Person (name: "Haagenti")
let animals = animals (age: 1
2) let personRow = Row (see: PersonView.self, model: person) {person, cell i print (person.name) } let animalRow = Row (see: AnimalView.self, model: animal) {animal, cell in print (animal.age) } la rader = [ // personRow animalRow ] la tableView = UITableView () for row in rows { tableView.register (row.view, forCellReuseIdentifier: String (describes: row.view)) leave indexPath = IndexPath (row: 0, section: 0) la cells = tableView.dequeue (row.view, for: indexPath) row.fill (row.model, cell) }

The code works, but when I activate animalRow Swift will complain. This is not so surprising since it cannot solve the types. I can't figure out how to get around this.

By using the following code I can declare everything once and perform all the parts as "fill" when I need them. I also want to add code like onTap etc, but I removed all this code to keep the problem clear.


Source link