I’ve quite a lot of varieties of cells to show in my UITableView
. I generate the reuseIdentifier
for the cells primarily based upon whether or not properties like title, physique, metadata, favicon and so forth are true or false. So, every property can have two states: true or false.
struct ReuseIdentifier : Codable, CustomStringConvertible {
var description : String {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
guard let information = attempt? encoder.encode(self), let str = String(information: information, encoding: .utf8) else {
return ""
}
return str
}
let sectionTitle : Bool
let title : Bool
let physique : Bool
let metadata : Bool
let favicon : Bool
let onCommentsPage : Bool
let indent : Bool
let collapsed : Bool
static var allPermutations : [ReuseIdentifier] {
var end result = [ReuseIdentifier]()
for i in 0..<(1 << 8) {// Discover how this must be hardcoded
end result.append(
ReuseIdentifier(
sectionTitle: (i >> 0) & 1 == 1,// Discover how all these must be hardcoded
title: (i >> 1) & 1 == 1,
physique: (i >> 2) & 1 == 1,
metadata: (i >> 3) & 1 == 1,
favicon: (i >> 4) & 1 == 1,
onCommentsPage: (i >> 5) & 1 == 1,
indent: (i >> 6) & 1 == 1,
collapsed: (i >> 7) & 1 == 1
)
)
}
return end result
}
}
extension String {
var decodedReuseIdentifier : ReuseIdentifier? {
guard let information = information(utilizing: .utf8), let d = attempt? JSONDecoder().decode(ReuseIdentifier.self, from: information) else {
return nil
}
return d
}
}
In my customized cell’s init, I decode the reuseIdentifier
String to the corresponding ReuseIdentifier
:
class Cell: UITableViewCell {
personal var slidingView = UIView()
var title : UILabel?
var physique : UILabel?
//....relaxation
override init(fashion: UITableViewCell.CellStyle, reuseIdentifier: String?) {
tremendous.init(fashion: fashion, reuseIdentifier: reuseIdentifier)
guard let decodedReuseIdentifier = reuseIdentifier?.decodedReuseIdentifier else {
print("Didn't decodedReuseIdentifier")
return
}
//Create every view primarily based upon whether or not decodedReuseIdentifier's variable is true or false
}
}
I take advantage of my ReuseIdentifier
‘s allPermutations
to register the corresponding reusable cell:
ReuseIdentifier.allPermutations.forEach { id in
tableView.register(Cell.self, forCellReuseIdentifier: id.description)
}
Then in my cellForRowAt
operate, I create the ReuseIdentifier
and deque a cell with it is String description:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Is there a extra common means for my allPermutations
operate? A way the place I haven’t got to specify every property identify and indexes? As you discover, I’m presently having to hardcode all of the property names in addition to the 8
and indexes.
Alternatively, is there a greater means to do that?