swift - Tableview 不显示我的附加数组,即使它们不为空

标签 swift uitableview firebase firebase-realtime-database tableview

我的问题是这样的:我可以从 firebase 加载所有内容,我可以将其附加到不同的数组中。但我无法让它显示在我的桌面 View 中。当我使用section时它不起作用,但是如果我将静态字符串插入到我的数组之一中,例如:accidentMessages:String = [“Hu”],那么Hu明显地在 TableView 中的“accident”部分下 在控制台中,它从 firebase 打印出我的消息,因此字符串(消息)必须已附加到我的数组中。但由于某种原因我无法在桌面 View 中展示它。 这是从 firebase 获取并添加到数组中的消息的控制台日志。 enter image description here

消息1应该在“帮助”中,消息2应该在威胁中,消息3应该在事故中。但不显示,只在控制台显示

var helpMessage: [String] = []
var threatMessage: [String] = []
var accidentMessage: [String] = ["Hu"]

var sectionMessages: [Int: [String]] = [:]
let sectionTitle = ["Help:", "Threat:", "Accident"]


sectionMessages = [0: helpMessage, 1: threatMessage, 2: accidentMessage]

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

    return (sectionMessages[section]?.count)!
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = UIColor.orange

    let image = UIImageView(image: sectionImages[section])
    image.frame = CGRect(x: 5, y: 5, width: 35, height: 35)
    view.addSubview(image)

    let label = UILabel()
    label.text = sectionTitle[section]
    label.frame = CGRect(x: 45, y: 5, width: 100, height: 35)
    view.addSubview(label)

    return view

}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 45
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    }

    cell!.textLabel?.text = sectionMessages[indexPath.section]![indexPath.row]

return cell!
}

最佳答案

sectionMessages 包含 3 个数组的副本,使用您为 sectionMessages 分配值时这些数组所具有的任何值。

如果您在初始化sectionMessages后需要修改这些数组,那么您需要直接在sectionMessages中修改它们,而不是修改原始数组。

或者你可以放弃 sectionMessages 并使用类似的东西

func messages(for section: Int) -> [String] {
    switch section {
    case 0: return helpMessage
    case 1: return threatMessage
    case 2: return accidentMessage
    default: return []
}

关于swift - Tableview 不显示我的附加数组,即使它们不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664856/

相关文章:

ios - 带有圆角的 UITableView 边框

ios - Swift: "Must call a designated initializer of the superclass"错误,即使代码正在这样做

ios - 返回我的播放器应用程序后没有声音

ios - 如何用数组中的颜色填充表格 View 单元格背景?

ios - 同一个 ViewController 中的 UITableView segue

swift - 如何在通过 Firebase (Swift) 创建用户之前检查电子邮件是否已被使用以及电子邮件格式是否错误

java.lang.ClassNotFoundException : org/eclipse/jetty/alpn/ALPN

javascript - 如何从 Firebase 数据库中选择 JSON 对象?

ios - Swift框架与Cocoapods——整合静态库

swift - 包含日文字符时缺少 TextField 字体样式