2017-04-01 177 views
2

在我的应用程序中,我使用xib文件自定义tableView单元格。我创建的.xib文件出口到我TableViewCell类UITableView和使用.xib的自定义UITableViewCell

标签等在我的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 
} 

我知道TableViews的工作方式是重复使用离开屏幕的单元格。他们的方式是我加载.xib并填充单元格是否正确?或者我必须添加一些东西给我的代码?

+0

是否有使用.xib的特定原因?您可以在Interface Builder的同一个表格视图中创建多个单元格。 – vadian

+0

我正在使用.xib,因为我将使用不同的单元格,具体取决于我拥有的数据 – pavlos

+0

问题在哪里?您可以使用不同的UI元素,大小等在相同的表视图中创建任意数量的单元格。只需将单元格拖动到表格视图中,并指定一个标识符和(可选)一个类。这比使用额外的.xibs更方便。 – vadian

回答

0

还有一件事是你需要在viewDidLoad方法中注册你的类重用标识符。

YourTable.registerclass(tablecell, forCellReuseIdentifier: "identifier" 

并确保您已连接所有必需的插座。在实现代码如下

let str1 : NSString = "StatementCell" 

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

+0

因此,这行代码基本上注册自定义单元类以便重用单元格? – pavlos

+0

是的,在我的代码中,我也用....在应用这个之前,我得到了一些崩溃,使用后它工作正常.... –

0

先注册自定义单元格nibCalss现在初始化tableviewcell

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

现在访问tableviewcell出口集合。

1

首先,你需要的UITableView

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

然后在UITableView的委托方法来注册你的自定义单元格cellForRowAt你需要写

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

现在你可以用cell.propertyName

访问您的UITableViewCell属性

您必须注意“cellIdentifier”和“forCellReuseIdentifier”的值都必须相同。

相关问题