swift - 快速将 TableView 添加到 .xib View 中

标签 swift uitableview nib

单击按钮时,我有一个 .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,但数据仅填充在第一个项目中。

屏幕截图

enter image description here

还有一件事我怎样才能设置 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/

相关文章:

objective-c - 将 .xib 文件添加到 UIViewController 子类?

swift - ios沙盒恢复非消耗性IAP无需购买

objective-c - 无法继承 UITableViewCell

swift - Swift 中 Localizable.strings 的最佳实践

ios - TableViewController 的pushViewController 方法中的navigationController = null (popover)

ios - 长按手势识别器仅在手指抬起时触发

iphone - 从 nib 加载自定义 UIView,nib 中包含的所有 subview 都是零?

ios - UIPageViewController 空白页

json - SwiftyJSON/Alamofire 未将字符串解析为 UTF8

objective-c - 如何在 Swift 项目中使用 Objective-C CocoaPods