swift加载xib的TableViewCell

class ViewController: UIViewController ,UITableViewDelegate ,UITableViewDataSource{

    override func viewDidLoad() {
        super.viewDidLoad()
        let _tableView = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), style: .Plain)
        _tableView.delegate = self
        _tableView.dataSource = self
        self.view .addSubview(_tableView)
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
            cell = NSBundle.mainBundle().loadNibNamed("MianTableViewCell", owner: nil, options: nil).last as? UITableViewCell
        return cell!
    }

第二种方式
其中MianTableViewCell,未xib的类名,

class MainViewController: UIViewController,UITableViewDelegate ,UITableViewDataSource {

    let cellID = "cell"
    var _tableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        _tableView = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), style: .Plain)
        _tableView.delegate = self
        _tableView.dataSource = self
        _tableView .registerNib(UINib.init(nibName: "MianTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        self.view .addSubview(_tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")
        return cell!
    }
swift加载xib的TableViewCell_第1张图片
xib中,identity要和,代码中cell的ID,保持一致.png

你可能感兴趣的:(swift加载xib的TableViewCell)