来自 Xib 的 Cell 与 Swift 3 [英] Cell from Xib with Swift 3

查看:27
本文介绍了来自 Xib 的 Cell 与 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读并观看了一些有关此主题的视频,但我无法使用它.我试图从 xib 而不是故事板中获取一个单元格.

I already read and saw some videos about this subject but i can't get this to work. Im trying to a cell from a xib instead of the storyboard.

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

This is my ViewController (where i have the Table View).

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;

    }

}

这是我的 CellTableView(我的 Cell 所在的类):

This is my CellTableView (the class where i have my 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
    }

}

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

I always used the Table View Cell inside the Table View on the StoryBoard but i want to try a XIB approach now.

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

I added the cell Identifier on the cell XIB to call it with the dequeueReusableCell method.

我可能做错了什么?我试图输出表视图的 dataSourcedelegate,但出现错误(我认为这不是正确的步骤).

What i could be doing wrong? I tried to Outlet the dataSource and the delegate of the Table View but i got an error (and i think its not the right steps).

推荐答案

您需要注册您的 nib 对象.

You need to register your nib object.

viewDidLoad()中:

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

tableView.register(nib, forCellReuseIdentifier: "yourIdentifier")

还需要返回节数:

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

这篇关于来自 Xib 的 Cell 与 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆