【问题标题】:swift 3 UITableView快速 3 UITableView
【发布时间】:2016-10-08 12:36:33
【问题描述】:

我是新手。
但我不明白为什么 UITableView 没有加载所有元素(数组中的 10 个元素)。
使用 Xcode7 有效,但使用 Xcode8 (Swift 3) 没有。
我重写了代码但无济于事:正在加载一个元素...

这是 UIViewController 内部的代码(扩展名为 UITableViewDelegate、UITableViewDataSource)

代码:

// MARK: UITableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return commentArray.count
}

// cell height
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true  
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = mytableView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath ) as! commentCell


    // connect objects with our information from arrays
    cell.usernameBtn.setTitle(usernameArray[indexPath.row], for: UIControlState.normal)
    cell.usernameBtn.sizeToFit()
    cell.commentLbl.text = commentArray[indexPath.row]
    return cell
}

我认为问题出在cellForRowAt....
我也有以下错误:

BFTask 在延续块中捕获到异常。不鼓励这种行为,并将在未来的版本中删除。捕获的异常:与 UITableView 一起使用的索引路径无效。传递给表视图的索引路径必须恰好包含两个指定节和行的索引。如果可能,请使用 UITableView.h 中 NSIndexPath 上的类别。

我不明白。 有人有想法吗? 谢谢

【问题讨论】:

  • func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { } 用这个方法替换你的这个方法并检查它
  • @HimanshuMoradiya 不,OP 有正确的 Swift 3 方法名称。
  • 是否添加了tableView.estimatedRowHeight = 40?你设置数据源了吗? tableView.dataSource = self?

标签: ios uitableview swift3


【解决方案1】:

您需要在 CellForRowAt IndexPath 中使用以下行:

let cellIdentifier = "CellComment"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as UITableViewCell?

【讨论】:

  • 你没有解释重要的部分。 OP 需要将mytableView 更改为tableView。无需使用cellIdentifier 常量。
【解决方案2】:

在 cellForRowAt indexPath 委托方法中将 mytableView 更改为 tableView 应该可以解决问题。

let cell = tableView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath ) as! commentCell

【讨论】:

    【解决方案3】:

    您的代码中可能存在一些问题。尝试解决/检查以下可能的错误:

    1. 根据您的错误,问题可能出在数组的下标上。试试这个:

      usernameArray[indexPath.section][indexPath.row]

    并且还使用委托:

    func numberOfSections(in tableView: UITableView) -> Int {
    
        return 1
    }
    
    1. 删除estimatedHeightForRowAt并在viewDidLoad()函数中添加以下代码

      tableView?.estimatedRowHeight = 135 //这个值应该最接近你的单元格高度。 tableView.rowHeight = UITableViewAutomaticDimension

    2. 您可能没有为 tableViewDataSource 和 tableViewDelegate 设置委托。从情节提要或 viewDidLoad() 方法中设置委托。

    【讨论】:

      猜你喜欢
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多