首页 > 解决方案 > TableViewCell does not get data in Swift

问题描述

I am using a Custom TableViewCell in TableViewController. Even the data is getting populated but my TableViewCell does not display it.

Here is my Custom TableViewCell Code

class PlaceItemCellCustom: UITableViewCell {

   @IBOutlet weak var placeFace: UILabel?
   @IBOutlet weak var placeName: UILabel?

   override func awakeFromNib() {
      super.awakeFromNib()
   } 

}

Here is my TableViewContoller

class PlaceListViewController: UITableViewController {

   override func viewDidLoad() {
      super.viewDidLoad()
      loadListFromSource()
   }
  
   // Other code

   override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
   }

   override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return places.count
   }

   override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return 100
   }

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let place = places[indexPath.row]
       // I am getting the data 
       print(place.placeName?.description ?? " " )
    
       let customCell = tableView.dequeueReusableCell(withIdentifier: "PlaceListIdentifier", for: indexPath) as! PlaceItemCellCustom
    
       customCell.placeName?.text = place.placeName
   
       return customCell
   }

}

What am I missing here? I am new to IOS app development. Found similar questions but did not help

Edit: It was working fine for the default TableViewCell.

But when I changed it to custom TableViewCell it does not work. I have set the class name in the storyboard as well.

Here is my Storyboard

enter image description here

Here is the output

enter image description here

标签: swiftxcodeuitableview

解决方案


据我所知,您一定忘记在IBOutletPlaceItemCellCustom 中连接 placeName:

在此处输入图像描述

在您的 PlaceItemCellCustom 中,将 placeName 保留为:

@IBOutlet weak var placeName: UILabel!

并在cellForRowAt

customCell.placeName.text = place.placeName

这样,如果您忘记连接 segue Xcode 将抛出错误:

线程 1:致命错误:在隐式展开可选值时意外发现 nil

你可以在这里读更多关于它的内容 :


推荐阅读