来自Xib和Swift 3的细胞

Adr*_*ian 12 uitableview xib swift

我已经阅读并看过一些关于这个主题的视频,但我无法让它发挥作用.我试图从xib而不是故事板的单元格.

这是我的ViewController(我有表视图).

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 5
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellTableView

        cell.test.text = "A";

        return cell;

    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的CellTableView(我有我的Cell的类):

import UIKit

class CellTableView: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    @IBOutlet var teste: UILabel!

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
Run Code Online (Sandbox Code Playgroud)

我总是在StoryBoard的Table View中使用Table View Cell,但我现在想尝试一种XIB方法.

我在单元格XIB上添加了单元格标识符,以使用dequeueReusableCell方法调用它.

我可能做错了什么?我试图Outlet dataSource和表视图的委托,但我得到一个错误(我认为它不是正确的步骤).

eLw*_*ner 45

您需要注册您的nib对象.

viewDidLoad():

let nib = UINib(nibName: "nameOfYourNibFile", bundle: nil)

tableView.register(nib, forCellReuseIdentifier: "yourIdentifier")
Run Code Online (Sandbox Code Playgroud)

您还需要返回部分的数量:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
Run Code Online (Sandbox Code Playgroud)

  • 对不起,我实际上是指你的nib文件的名称.你的情况应该是"CellTableView"...... (2认同)
  • 这是一个直接的答案.我是我的情况,我的tableview使用3种类型的单元格:cType1,cType2,cType3.有没有办法注册这些自定义单元格并重复使用相同的标识符?或者我应该用3种不同的标识符注册它们然后检查每一行,以便重用匹配的cellId? (2认同)