自定义TableViewCell中的标签始终返回其初始化值

时间:2018-01-30 06:59:16

标签: ios swift uitableview xib nib

我对Swift相当新,并且已经广泛研究了以下问题,但未成功。

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

XIB / NIB screenshot

 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
        }
    }

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

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")
}

最后,我添加了一个TableView,它使用自定义ConversationCell到我的类HomeTabViewController,这是一个ViewController,同时充当TableView的源代码和委托。

请查看下面的代码,其中我在func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)内的单元格中打印标签的内容。

而不是返回我在初始化会话数组时定义的标签值(即"第一次对话","第二次对话","第三次对话& #34; - 在运行时在TableView中正确显示),它返回在NIB文件中定义的默认标签文本值(即"我们面前的景象确实是崇高的。")。 Simulator + Console output

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文件的相应默认文本值。

知道为什么(地狱)这是怎么回事? :) 非常感谢!

5 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

问题不是一个问题,你不只是访问正确的东西,你应该做的是使用tableview函数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)")
 }

答案 2 :(得分:0)

这样做..

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

答案 3 :(得分:0)

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文件中设计的单元格相同。

您应该在表视图中获取与索引路径对应的单元格,而不是将新单元格出列:

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

或者只是访问您已获得的阵列:

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

答案 4 :(得分:0)

您只将值传递给主题,

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)

尝试这样做,

Could You Please try Following code with the css.You change the css with your own needs.

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    .container {
      position: relative;
      width: 50%;
    }

    .image {
      display: block;
      width: 100%;
      height: auto;
    }

    .overlay {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      height: 100%;
      width: 100%;
      opacity: 0;
      transition: .5s ease;
      background-color: #008CBA;
    }

    .overlay:hover {
     opacity: 1;
}

    .text {
      color: white;
      font-size: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
      text-align: center;
    }
    </style>
    </head>
    <body>

    <div class="container">
    <a href="<?php the_permalink(); ?>">
    <?php if ( has_post_thumbnail() ) : ?>
    <?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
        <img alt="Avatar" class="image"> src="<?php echo $feat_image; ?>" />
    <?php else: ?>
    <?php $feat_image = get_stylesheet_directory_uri() . '/assets/images/default.jpg'; ?>
        <img alt="Avatar" class="image">src="<?php echo $feat_image; ?>" />
    <?php endif; ?>
      <div class="overlay">
        <div class="text"><?php the_title(); ?></div>
      </div>
    </a>
    </div>

    </body>
    </html>

谢谢..!