【问题标题】:Cell from Xib with Swift 3来自 Xib 的单元格与 Swift 3
【发布时间】:2017-03-09 10:19:50
【问题描述】:

我已经阅读并看过一些关于这个主题的视频,但我无法让它发挥作用。我正在尝试从 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;

    }

}

这是我的 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
    }

}

我一直在 StoryBoard 的表格视图中使用表格视图单元格,但我现在想尝试 XIB 方法。

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

我可能做错了什么?我尝试输出 dataSource 和 Table View 的 delegate,但出现错误(我认为这不是正确的步骤)。

【问题讨论】:

    标签: swift uitableview xib


    【解决方案1】:

    您需要注册您的 nib 对象。

    viewDidLoad():

    let nib = UINib(nibName: "nameOfYourNibFile", bundle: nil)
    
    tableView.register(nib, forCellReuseIdentifier: "yourIdentifier")
    

    您还需要返回节数:

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

    【讨论】:

    • 您的意思是单元格标识符,对吗?所以在 ViewController 我只需要输入: let nib = UINib(nibName: "cell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "cell") ?它没有用。我的单元格还是空的。
    • 对不起,我实际上是指您的 nib 文件的名称。在你的情况下应该可能是“CellTableView”......
    • 这是一个直接的答案。我是我的情况,我的表格视图使用 3 种类型的单元格:cType1、cType2、cType3。有没有办法注册这些自定义单元格并使用相同的标识符重用它们?或者我应该用 3 个不同的标识符注册它们,然后检查每一行,然后重用匹配的 cellId?
    • 我在使用tableView.register(MyCell.self, forCellReuseIdentifier: identifier),但一直没用,这让我快疯了。注册笔尖就可以了。
    • @Koen 是的,你是对的。还有一个技巧,当我完全以编程方式创建我的自定义UITableViewCell,UICollectionViewCell 时,不需要识别 nib,只需编写自定义类,然后编写它的 self 参数。这对我来说是一个习惯,对我来说我没有意识到当你使用 Xib 文件时,Xcode 必须识别 Xib 文件的名称,而不仅仅是自定义类名。
    【解决方案2】:

    首先,您必须注册您的 nib 对象。

    yourTable?.register(UINib(nibName: "yourCustomCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")
    

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 2015-04-10
      相关资源
      最近更新 更多