在Swift中寻找在数组数组中使用不同标头的替代方法



我有一个程序可以完全工作,只是我得到了一个关于需要更改的注释。

此程序包含一个数组。在应用程序中,每个部分都有不同的标题。标头名称在称为"的单独数组中;myTitles";。用户希望标头不使用任何重写方法。我该如何更改?我拥有它的方式是我做过的唯一方式。

有人告诉我"标题(标题(应该是一个字符串">

数组代码(供参考(:

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")]
]

标头阵列:

let myTitles: [String] = ["PEOPLE", "ANIMALS", "FOOD", "OTHER"]

问题代码(当前标头覆盖方法(:

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
}

您需要使用可选的数据源方法func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

只需返回数组中的字符串,而不是将其形成视图。

(FWIW我更喜欢你的方法!(

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.myTitles.count
}

最新更新