【问题标题】:uiTableview cell is not displaying in view controlleruiTableview 单元格未显示在视图控制器中
【发布时间】:2017-03-22 11:50:47
【问题描述】:

我有 ViewController,其中有 UITableview 和自定义单元格。我的代码是正确的,我也做了委托和数据源。我在 tableViewCell 中也有 IBoutlets。 我只会看到空行,我也看不到故事板中设置的单元格背景颜色。

class HomeVC: UIViewController , UITableViewDataSource , UITableViewDelegate  {

@IBOutlet weak var profileImg: UIImageView!
@IBOutlet weak var fullnameLbl: UILabel!
@IBOutlet weak var emailLbl: UILabel!
@IBOutlet weak var usernameLbl: UILabel!
@IBOutlet weak var editprofileBtn: UIButton!

var tableData = [AnyObject]()
var username = String()

@IBOutlet var homeSwipe: UISwipeGestureRecognizer!
@IBOutlet weak var tableView: UITableView!
var pflegerId = String()

var weekday = Date().dayOfWeek()

@IBAction func swipe(_ sender: Any) {

}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self


   //Swipe gesture

     username = (user!["username"] as AnyObject).uppercased
    let fullname = user!["fullname"] as? String
    let email = user!["email"] as? String
   pflegerId = (user!["id"] as? String)!

    usernameLbl.text = username
    fullnameLbl.text = fullname
    emailLbl.text = email

    loadData(username : username)



}

func loadData(username : String) {


    let url = URL(string: "http:..")


    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    let body = "Id=\(pflegerId)"

    request.httpBody = body.data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        if error == nil {

            DispatchQueue.main.async(execute: {

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    print(json)


                    guard let parseJSON = json else {
                        print("")
                        return
                    }

                    guard let posts = parseJSON["posts"] as? [AnyObject] else{
                        print("error while parseJSON")
                        return
                    }


                    self.tableData = posts

                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }


                }catch {
                    //print("Caught an error: \(error)")
                    DispatchQueue.main.async(execute: {
                        let message = ""
                        appDelegate.infoView(message: message, color: colorSmoothRed)
                    })
                }
            })


        }else {
            //print("error: \(error)")
            DispatchQueue.main.async(execute: {
                let message = error!.localizedDescription
                appDelegate.infoView(message: message, color: colorSmoothRed)
            })

        }
        }.resume()

}





@IBAction func logout_click(_ sender: Any) {
    //alle Daten löschen
    UserDefaults.standard.removeObject(forKey: "parseJSON")
    UserDefaults.standard.synchronize()

    //jetzt wieder zur Login Ansicht wechseln.
    let loginvc = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    self.present(loginvc, animated: true, completion: nil)


}


//TABLEVIEW

func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

//Total number of Rows in Table
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print(tableData.count)
    return tableData.count


}





func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! todaysPatientsListCell

    // Configure the cell...
    let tableData = self.tableData[indexPath.row]
    cell.patientNameLbl?.text = tableData["name"] as? String
    cell.addressLbl?.text = tableData["address"] as? String
    cell.timeLbl?.text = tableData["timing"] as? String

    return cell

}





func coolSwiped(_ swipe : UISwipeGestureRecognizer) {

    if swipe.direction == .right {
        DispatchQueue.main.async {
            appDelegate.swipeToTomorrow()
            self.tableView.reloadData()
        }
    }
    else if swipe.direction == .left {
        DispatchQueue.main.async {
            appDelegate.swipeToYesterday()
            self.tableView.reloadData()

        }
    }

}

}

【问题讨论】:

  • 检查您的tableData 数组是否为空。
  • 不,它不是空的。它从服务器端获取值。我已经更新了我的代码,你可以检查它。
  • 对我来说有一段时间发生了,我实现了协议,但忘记在故事板中引用它们。
  • 检查表出口和代表是否正确连接,然后使用我回答中的给定代码。
  • 您是否在调试器中检查过您的UITableView 委托方法是否被调用?如果是,numberOfRowsInSection 返回时的值是多少?

标签: ios swift xcode uitableview


【解决方案1】:

我认为您应该为行指定行高。

ex.- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60.0;
}

大部分解决了您的问题。如果没有解决,请告诉我。

谢谢 尼拉夫·扎拉瓦迪亚

【讨论】:

  • 为什么需要这个?该表将使用 Storyboard 中设置的 rowHeight。
【解决方案2】:

我有两个问题要问你:

  1. 您可以对数组进行硬编码并检查吗?这将消除服务器问题。
  2. todaysPatientsListCell 是否已分配给 Storyboard 中的自定义单元格?

如果他们有帮助,请告诉我。

【讨论】:

    【解决方案3】:

    当您在获取数据后重新加载数据时,您需要在主线程中执行此操作。所以替换这一行:

    self.tableView.reloadData()
    

    以下内容:

    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
    

    【讨论】:

    • 代码中没有任何内容表明它是在后台队列中调用的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多