簡體   English   中英

swift 3 UITableView

[英]swift 3 UITableView

我是新手。
但我不明白為什么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上的類別。

我不明白。 有沒有人有想法? 謝謝

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

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

將mytableView更改為tableView內的cellForRowAt indexPath委托方法應解決此問題。

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

您的代碼中可能存在一些問題。 嘗試解決/檢查以下可能的錯誤:

  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設置委托。 從storyboard或viewDidLoad()方法設置委托。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM