自定义 TableViewCell 中的标签总是 return 它们的初始化值

Labels in custom TableViewCell always return their initialization values

我是 Swift 的新手,对以下问题进行了广泛但未成功的研究。

我创建了一个名为 ConversationCell 的自定义 TableViewCell class,并在 NIB/XIB 文件中定义了它的 UI。

 import UIKit
    import SwipeCellKit

    class ConversationCell: SwipeTableViewCell {

        @IBOutlet weak var distanceLabel: UILabel!
        @IBOutlet weak var locationLabel: UILabel!
        @IBOutlet weak var subjectLabel: UILabel!
        @IBOutlet weak var bodyLabel: UILabel!
        @IBOutlet weak var profileImageView: UIImageView!
        @IBOutlet weak var usernameLabel: UILabel!
        @IBOutlet weak var starImageView: UIImageView!
        @IBOutlet weak var dateLabel: UILabel!

        var isFollowed = false

        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
    }

然后我写了一个简单的class,命名为Conversation,它是ConversationCell 的模型class。

class Conversation {
    var distance = "123 ft."
    var location = "123 Market St"
    var date = "Yesterday, 10:45AM"
    var subject = "Default subject."
    var body = "Default body"


   // var subject = "My Subject"
    //var body = "My Body"

    var username = "worldsurfer"
    var profilePhoto = UIImage(named: "profilePhoto")
}

最后,我添加了一个使用自定义 ConversationCellTableView 到我的 class HomeTabViewController,这是一个 ViewController 作为来源并代表 TableView。

请看下面的代码,我在 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath).

的单元格中打印了标签的内容

而不是返回我在初始化我的对话数组时定义的标签值(即“第一个对话”、“第二个对话”、“第三个对话”——它们在运行时正确显示在 TableView 中),它 returns NIB 文件中定义的默认标签文本值(即 "The spectable before us was indeed sublime.")。

import UIKit
import SwipeCellKit

class HomeTabViewController: CoreDesignViewController {
    @IBOutlet weak var tableView: UITableView!

    var conversationArray : [Conversation] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UINib(nibName: "ConversationCell", bundle: nil), forCellReuseIdentifier: "homeTabCell")

        tableView.dataSource = self
        tableView.delegate = self


        let conversation1 = Conversation()
        conversation1.subject = "1st conversation"
        conversationArray.append(conversation1)

        let conversation2 = Conversation()
        conversation2.subject = "2nd Conversation"
        conversationArray.append(conversation2)

        let conversation3 = Conversation()
        conversation3.subject = "3rd conversation"
        conversationArray.append(conversation3)

        tableView.estimatedRowHeight = tableView.rowHeight
        tableView.rowHeight = UITableViewAutomaticDimension

        self.showNavBar()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

extension HomeTabViewController: UITableViewDataSource, UITableViewDelegate, SwipeTableViewCellDelegate{


    //MARK: - UITableViewDataSource Protocol Implementation
    /***************************************************************/


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return conversationArray.count
    }

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


        guard let cell = tableView.dequeueReusableCell(withIdentifier: "homeTabCell", for: indexPath) as? ConversationCell
        else{
            fatalError("The dequeued cell is not an instance of homeTabCell.")
        }

        //To make the cell Swipeable via SwipeCellKit
        cell.delegate = self


        print("CELL_FOR_ROW_AT - indexPath.row = \(indexPath.row) | Conversation.subject = \(conversationArray[indexPath.row].subject)")

        //Initializing the cell
        cell.distanceLabel.text = conversationArray[indexPath.row].distance
        cell.locationLabel.text = conversationArray[indexPath.row].location
        cell.dateLabel.text = conversationArray[indexPath.row].date
        cell.subjectLabel.text = conversationArray[indexPath.row].subject
        cell.bodyLabel.text = conversationArray[indexPath.row].body
        cell.usernameLabel.text = conversationArray[indexPath.row].username
        cell.profileImageView.image = conversationArray[indexPath.row].profilePhoto

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


        guard let cell = tableView.dequeueReusableCell(withIdentifier: "homeTabCell", for: indexPath) as? ConversationCell
            else{
                fatalError("The dequeued cell is not an instance of homeTabCell.")
        }
         print("DID_SELECT_ROW_AT - Selected Row = \(indexPath.row) | cell.subjectLabel.text = \(cell.subjectLabel.text!)")
 }

我在自定义单元格中尝试了所有不同的标签,结果相同:它总是打印出 XIB 文件的相应默认文本值。

知道为什么(见鬼)会这样吗? :) 非常感谢!

conversationArray 添加数据时,您只是插入修改后的 subject。更新 all 其他属性以及 belo:-

let conversation1 = Conversation()
        conversation1.subject = "1st conversation"
conversation1.location = "India"
conversation1.distance= "456 Ft"
conversation1.date= "Yesterday, 11:15PM"
        conversationArray.append(conversation1)

您需要为所有对话对象分配属性值,即 conversation2conversation3

问题不完全是问题,您不只是在访问正确的内容,您应该做的是使用表视图函数 didSelect 提供的索引路径访问对话单元格。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    guard let cell = tableView.dequeueReusableCell(withIdentifier: "homeTabCell", for: indexPath) as? ConversationCell
        else{
            fatalError("The dequeued cell is not an instance of homeTabCell.")
    }
     print("DID_SELECT_ROW_AT - Selected Row = \(indexPath.row) | cell.subjectLabel.text = \(conversationArray[indexPath.row].subject)")
 }

这样做..

  let cell = tableView.cellForRow(at: indexPath)
  print(cell.label.text)

看看你在做什么 didSelectRowAt

guard let cell = tableView.dequeueReusableCell(withIdentifier: "homeTabCell", for: indexPath) as? ConversationCell
    else{
        fatalError("The dequeued cell is not an instance of homeTabCell.")
}

您正在使 单元格出队!从 dequeueReusableCell 返回的单元格始终与您在 XIB 文件中设计的单元格相同。

您应该在 table 视图中获取对应于索引路径的单元格,而不是使新单元格出队:

let cell = tableView.cellForRow(at: indexPath)
// print cell contents...

或者只访问您拥有的数组:

let conversation = conversationArray[indexPath.row]
// print conversation's properties...

您只将值传递给主题,

    let conversation1 = Conversation()
    conversation1.subject = "1st conversation"
    conversationArray.append(conversation1)

所以主题随着更新值而改变,其他保持默认值

class Conversation {
var distance = "123 ft."
var location = "123 Market St"
var date = "Yesterday, 10:45AM"
var subject = "Default subject."
var body = "Default body"


   // var subject = "My Subject"
   // var body = "My Body"

var username = "worldsurfer"
var profilePhoto = UIImage(named: "profilePhoto")
}

尝试这样捐赠,

    let conversation1 = Conversation()
    conversation1.subject = "1st conversation"
    conversation1.distance = "500 ft."
    conversation1.location = "2nd West Street"
    conversation1.date = "Yesterday, 4:00 PM"
    conversation1.body = "1st conversation body, just a Try"
    conversation1.username = "ben"
    conversationArray.append(conversation1)

    let conversation2 = Conversation()
    conversation2.subject = "2nd conversation"
    conversation2.distance = "160 ft"
    conversation2.location = "New Southern Street"
    conversation2.date = "Yesterday, 11:45 AM"
    conversation2.body = "2nd conversation body, just a Try"
    conversation2.username = "Abirami"
    conversationArray.append(conversation2)

谢谢..!