单击按钮时,我有一个 .xib View ,在其中定义了一个 tableView。在这里,我为单元格创建了另一个 .xib 文件,因为只有 option 。我认为没有默认单元格..那么如何在表格 View 单元格中显示项目。 我已经像这样注册了 .Xib 并尝试了但得到的结果令人惊讶。
class CustomAddOnVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
let items = ["pk","ak","sk"]
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell: CustomOneCell! = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath: indexPath) as? CustomOneCell
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomOneCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath:indexPath ) as? CustomOneCell
cell.addOnName.text = items[indexPath.row]
cell.addOnPrice.text = "£0.0"
}
return cell
}
这里的项目计数为 3,但数据仅填充在第一个项目中。
屏幕截图
还有一件事我怎样才能设置 View 的高度直到所有项目的末尾?正如您可以看到项目后面有额外的空间。如果我减小尺寸并且出现更多项目,那么同样的问题再次出现。我想根据项目数据动态设置高度
最佳答案
我认为这是因为当您第一次注册时它不再输入您的cell == nil
。因此,我的建议是将更新文本移到 if 语句之外。像这样:
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomOneCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier,forIndexPath:indexPath ) as? CustomOneCell
}
cell.addOnName.text = items[indexPath.row]
cell.addOnPrice.text = "£0.0"`
关于swift - 快速将 TableView 添加到 .xib View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38609104/