【问题标题】:Rows are empty in tableview swifttableview swift中的行为空
【发布时间】:2020-11-04 02:25:03
【问题描述】:

所以,我正在尝试将数据从 sqlserver 获取到我的 tableview 但我似乎没有得到它我遵循了一个教程并且很确定我没有做错我也在使用自定义单元格,唯一有效的是连接到 sql 因为它在输出日志中打印数据我对 swift 和 xcode 真的很陌生,我不知道我在做什么。 无论如何,这是我的代码:

TableCell.swift

import UIKit

class TableCell: UITableViewCell {

    @IBOutlet weak var idtext: UILabel!
    @IBOutlet weak var usernametxt: UILabel!
    
    func setText(text: textstuff) {
        idtext.text = text.id
        usernametxt.text = text.username
    }
    
    
    
}

视图控制器

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tableview: UITableView!
    var taable: [textstuff] = []

    
    override func viewDidLoad() {
        super.viewDidLoad()
        taable = createArray()
        
        //Adding the observer for error and to receive the message
       
          }
    
    func createArray() -> [textstuff]{
        var temptext: [textstuff] = []
        NotificationCenter.default.addObserver(self, selector: #selector(error(_:)), name: NSNotification.Name.SQLClientError, object: nil)
               NotificationCenter.default.addObserver(self, selector: #selector(message(_:)), name: NSNotification.Name.SQLClientMessage, object: nil)
               
               let client = SQLClient.sharedInstance()!
                         client.connect("x.x.x.x", username: "xxxxxx", password: "xxxxxx", database: "xxxxxx") { success in
                         client.execute("SELECT username FROM Supervisors", completion: { (_ results: ([Any]?)) in
                          for table in results as! [[[String:AnyObject]]] {
                              for row in table {
                                  for (columnName, value) in row {
                                      print("\(columnName) = \(value)")
                                     let newVal = value as? String ?? ""
                                    let userandid = textstuff(id: columnName, username: newVal)
                                    temptext.append(userandid)
                                    
                                  }
                              }
                          }
                          client.disconnect()
                      })
                  }
        return temptext
    }
    
   
  
    @objc func error(_ notification: Notification?) {
     let code = notification?.userInfo?[SQLClientCodeKey] as? NSNumber
     let message = notification?.userInfo?[SQLClientMessageKey] as? String
     let severity = notification?.userInfo?[SQLClientSeverityKey] as? NSNumber
     if let code = code, let severity = severity {
         print("Error #\(code): \(message ?? "") (Severity \(severity))")
     }
 }

    @objc func message(_ notification: Notification?) {
        let message = notification?.userInfo?[SQLClientMessageKey] as? String
        print("Message: \(message ?? "")")
    }
}

extension ViewController:UITableViewDataSource, UITableViewDelegate{
       
       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return taable.count
       }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let text = taable[indexPath.row]
               
               let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TableCell
               
               
               cell.setText(text: text)
               
               return cell
    }
    
    
       
   }

textstuff.swift

import Foundation
class textstuff{
    
    var id: String
    var username: String
    
    init(id: String, username: String) {
        self.id = id
        self.username = username
    }
    
}

非常感谢任何帮助!

编辑 我尝试打印 taable.count 并按预期打印 0

【问题讨论】:

  • 是的,如果 taable.count 为 0,您的表将为空。尝试将一些虚拟数据放入 taable 以查看您的表格视图是否有效,然后您可以研究为什么没有将您期望的数据放入数组中。
  • @Corbell 抱歉,我对 swift 非常陌生...如何添加虚拟数据?
  • 另外,我建议您将数据数组称为“taable”之外的其他名称,这非常令人困惑的命名方案。像“textData”这样的东西呢?
  • @Corbell 实际上是个好主意
  • @Corbell 刚刚改了名字,但是我怎样才能添加虚拟数据呢?

标签: ios arrays swift uitableview


【解决方案1】:

你陷入了异步陷阱。您不能从异步任务中返回某些内容作为方法的返回值。返回的数组将始终为空。

在这种情况下,解决方案非常简单。在完成处理程序结束时,将结果分配给数据源数组并重新加载表视图。

viewDidLoad 替换为

override func viewDidLoad() {
    super.viewDidLoad()
    createArray()
}

createArray 替换为

func createArray() {
    var temptext: [textstuff] = []
    NotificationCenter.default.addObserver(self, selector: #selector(error(_:)), name: NSNotification.Name.SQLClientError, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(message(_:)), name: NSNotification.Name.SQLClientMessage, object: nil)
           
    let client = SQLClient.sharedInstance()!
    client.connect("x.x.x.x", username: "xxxxxx", password: "xxxxxx", database: "xxxxxx") { success in
        client.execute("SELECT username FROM Supervisors", completion: { (_ results: ([Any]?)) in
             for table in results as! [[[String:AnyObject]]] {
                 for row in table {
                     for (columnName, value) in row {
                         print("\(columnName) = \(value)")
                         let newVal = value as? String ?? ""
                         let userandid = textstuff(id: columnName, username: newVal)
                         temptext.append(userandid)
                                
                     }
                 }

             }
             self.taable = temptext
             DispatchQueue.main.async {
                 self.tableview.reloadData()
             }
             client.disconnect()
        })
    }
}

并且请遵守命名约定以及以大写字母开头的结构和类 (Textstuff)

【讨论】:

  • 兄弟,你真是个救命恩人,非常感谢!!!!
猜你喜欢
  • 1970-01-01
  • 2017-06-29
  • 2016-08-22
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多