【问题标题】:Custom cell content doesn't show Swift自定义单元格内容不显示 Swift
【发布时间】:2017-06-01 16:31:33
【问题描述】:

我想创建一个自定义表格视图。我有一个 UITableViewController:

class MainListView: UITableViewController{
var invoceList: [InvoceObject] = []
@IBOutlet var tbMain: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
    tbMain.delegate = self
    self.tbMain.dataSource = self
    }

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell        
    cell.lblBuyerName?.text = self.invoceList[indexPath.row].BUYER_NAME
    cell.lblDate?.text = self.invoceList[indexPath.row].CREATED_AT
    cell.lblPriceGross?.text = self.invoceList[indexPath.row].PRICE + " " + self.invoceList[indexPath.row].CURRENCY

    cell.backgroundColor = UIColor(white: 1, alpha: 0.5)      
    return cell
    }
}

还有我的 UITableViewCell 类:

class CustomCell: UITableViewCell {
@IBOutlet weak var lblBuyerName: UILabel!
@IBOutlet weak var lblDate: UILabel!
@IBOutlet weak var lblPriceGross: UILabel!   

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}
}

构建后,我得到一个空单元格。我有许多行,例如 invoceList.count,但没有标签,它看起来像空表。我做错了什么?

【问题讨论】:

  • 你是如何初始化invoceList数组的?
  • @NiravD 没关系,因为如果我使用cell.textLabel?.text(没有自定义单元格)一切都很好。

标签: ios xcode uitableview swift3 custom-cell


【解决方案1】:

由于您使用的是UITableViewController,因此有一个隐含的tableView 属性与连接的数据源和委托。您应该使用它来避免混淆。

如果您使用的是原型单元格,请删除 self.tableView.register... 行。

【讨论】:

    【解决方案2】:

    如果单元格的内容是在单独的 xib 文件中定义的,您需要注册它,而不是类 - 如果您只注册类,则不会创建实际标签,因为类本身不会创建它们。

    //Replacing CustomCellNibName with the name of your xib file
    tableView.register(UINib.init(nibName: "CustomCellNibName", bundle: nil), forCellReuseIdentifier: "Cell")
    

    如果单元格在故事板中创建为原型单元格,则无需注册它,只需将类与故事板文件中的单元格关联(在身份检查器选项卡下,自定义类),然后填写在属性检查器字段标识符下您要使用的名称(在本例中为“单元格”)。

    【讨论】:

    • 在故事板中创建的单元格作为原型单元格并与我的 CustomCell.swift 类相关联。 ID 是“细胞”。
    • 如果你删除“self.tableView.register”行,它应该可以工作
    • 就我而言,一切都是正确的,除了我注册手机的方式。它是在 xib 文件中定义的,但我尝试通过 XXXCell.self 注册它,结果无法看到数据。谢谢@davedavedave,你的回答很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2013-11-21
    • 1970-01-01
    相关资源
    最近更新 更多