简体   繁体   English

UITableView 和自定义 UITableViewCell 使用 .xib

[英]UITableView and custom UITableViewCell using .xib

In my app I am using a custom tableViewCell using a xib file.在我的应用程序中,我使用了一个使用 xib 文件的自定义 tableViewCell。 I create the .xib file outlet the labels etc to my TableViewCell class我创建了 .xib 文件出口标签等到我的 TableViewCell 类

In my ViewController the code I used to populate and show the cell on the table view is as follows:在我的 ViewController 中,我用来在表格视图中填充和显示单元格的代码如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell
    
    
    
    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)
    
    return cell
}

I am aware that the way tableViews work is that they reuse the cell that goes off the screen.我知道 tableViews 的工作方式是它们重用离开屏幕的单元格。 Is the way i am loading the .xib and populating the cell correct?我加载 .xib 并填充单元格的方式是否正确? Or do I have to add something to my code?还是我必须在我的代码中添加一些东西?

First you need to register your custom cell with UITableView首先,您需要使用 UITableView 注册您的自定义单元格

yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")

then in UITableView Delegate method cellForRowAt you need to write然后在 UITableView 委托方法 cellForRowAt 你需要写

let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell

now you can access your UITableViewCell properties with cell.propertyName现在您可以使用 cell.propertyName 访问您的 UITableViewCell 属性

and you must take care that "cellIdentifier" and "forCellReuseIdentifier" both value must be same.并且您必须注意“cellIdentifier”和“forCellReuseIdentifier”两个值必须相同。

One more thing is you need to register your class for reuse identifier in viewDidLoad method.另一件事是您需要在viewDidLoad方法中注册您的类以重用标识符。

YourTable.registerclass(tablecell, forCellReuseIdentifier: "identifier"

And make sure you have connect all the required outlets.并确保您已连接所有必需的插座。

FIrst Register Custom cell nibCalss in tableview首先在表格视图中注册自定义单元格 nibCalss

let str1 : NSString = "StatementCell"

tableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: str1 as String)

Now initialise tableviewcell现在初始化 tableviewcell

let cell1:StatementCell = tableView.dequeueReusableCell(withIdentifier: str1 as String) as! StatementCell!

Now access tableviewcell outlet collection.现在访问 tableviewcell 插座集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM