[英]How to pass data From VC to Cell?
我想知道如何將數據從ViewController傳遞到單元格?
我是一個初學者,所以我可以監督明顯的:P
我有一個家用VC,當您按commentButton時,您會進入CommentVC,其中包含帖子的postId。 因為我想能夠喜歡一個comment(效果很好)並注意到用戶喜歡他的評論(目前不起作用),所以我不僅需要在commentVC中擁有postId(該ID可以保存正確的),也可以在單元格中。
這是我將數據從HomeVc傳遞到CommentVC的代碼
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CommentSegue" {
let commentVC = segue.destination as! CommentViewController
let commentCell = CommentTableViewCell()
let postId = sender as! String
commentCell.postId = postId
commentVC.postId = postId
}
}
當我在CommentVc和CommentCell中打印兩個變量時,只有CommentVc顯示正確的變量,而單元格的打印語句為“ nil”。
知道我如何通過嗎?
您不應通過調用自定義類初始化程序來實例化UITableViewCell
,而應在UITableViewController
類(或符合UITableViewContollerDataSource
協議的類)中進行初始化。
使用dequeueReusableCell(withIdentifier:)
創建單元格時,將要顯示在單元格中的數據傳遞到表視圖控制器和數據源方法(例如tableView(_:cellForRowAt:)
)中,將數據分配給特定的單元格。
您在哪里執行打印聲明? 通常,建議將任何數據傳遞到TableView
委托方法的cellForRow
中的單元格視圖。 在單元類內部,可以有一個configure(_ myId: String)
方法,其id作為要傳遞的參數之一。然后在該方法中打印它。
您不應傳遞表格單元格。 由於您已經將postId傳遞給了注釋視圖控制器,因此您可以通過這種方式從注釋視圖控制器中的表格視圖單元格訪問此ID。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EditorFontCell") as! EditorFontCell
print(self.postId)
//do what you want with postId with the current cell object here
return cell
}
現在移去segue中的細胞
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CommentSegue" {
let commentVC = segue.destination as! CommentViewController
let postId = sender as! String
commentVC.postId = postId
}
}
//In cell table cell class create a variable to hold the data. Here I made postId as String variable.
class EditorFontCell: UITableViewCell{
var postId: String! // postId may be other type
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
// in this method you create an object i.e. cell, of type EditorFontCell
// and you can access that postId by this tableCell object. You can simple assign a value to as shown below.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EditorFontCell") as! EditorFontCell
cell.postId = "String data"
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.