I have a program that fully works except I was given a note about something that needed changed.
This program contains an array of arrays. In the app each section has a different header. The header names are in a separate array called "myTitles". The user wants the headers to not be using any override methods. How do I change this? The way I have it is the only way I have ever done it.
I was told; "The title (headers) should be a string."
Array of Arrays code (for reference):
var emojis: [[Emoji]] = [
[Emoji(symbol: "😀", name: "Grinning Face", description: "A typical smiley face.", usage: "happiness"),
Emoji(symbol: "😕", name: "Confused Face", description: "A confused, puzzled face.", usage: "unsure what to think; displeasure"),
Emoji(symbol: "😍", name: "Heart Eyes", description: "A smiley face with hearts for eyes.", usage: "love of something; attractive"),
Emoji(symbol: "👮", name: "Police Officer", description: "A police officer wearing a blue cap with a gold badge. He is smiling, and eager to help.", usage: "person of authority")],
[Emoji(symbol: "🐢", name: "Turtle", description: "A cute turtle.", usage: "Something slow"),
Emoji(symbol: "🐘", name: "Elephant", description: "A gray elephant.", usage: "good memory")],
[Emoji(symbol: "🍝", name: "Spaghetti", description: "A plate of spaghetti.", usage: "spaghetti")],
[Emoji(symbol: "🎲", name: "Die", description: "A single die.", usage: "taking a risk, chance; game"),
Emoji(symbol: "⛺️", name: "Tent", description: "A small tent.", usage: "camping"),
Emoji(symbol: "📚", name: "Stack of Books", description: "Three colored books stacked on each other.", usage: "homework, studying"),
Emoji(symbol: "💔", name: "Broken Heart", description: "A red, broken heart.", usage: "extreme sadness"),
Emoji(symbol: "💤", name: "Snore", description: "Three blue \'z\'s.", usage: "tired, sleepiness"),
Emoji(symbol: "🏁", name: "Checkered Flag", description: "A black and white checkered flag.", usage: "completion")]
]
Header Array:
let myTitles: [String] = ["PEOPLE", "ANIMALS", "FOOD", "OTHER"]
Code in Question (current header override methods):
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let label = UILabel()
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = myTitles[section]
label.font = .systemFont(ofSize: 14)
label.textColor = .gray
headerView.addSubview(label)
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
You need to use the optional datasource method
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
and just return the string from your array, rather than forming it into a view.
(FWIW I prefer your approach!)