首页 > 解决方案 > 在 tableView 中使用特定的 UITableViewCellStyle 单元格并将它们出列

问题描述

我正在尝试在单元格标题下方打印出我的单元格详细文本标签。这是我运行时没有错误的所有代码,只是没有出现详细标签。我尝试了其他论坛的解决方案,包括这个,没有任何效果。我真的不知道为什么会这样?也许它在我的 cellForRowAt 函数中

class LoginController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return discussionTitles.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
        cell.backgroundColor = UIColor.clear
        cell.textLabel?.text = discussionTitles[indexPath.row]
        cell.detailTextLabel?.text = discussionDescriptions[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Discussion Board"
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.hideKeyboardWhenTap()
        view.backgroundColor = UIColor(red: 203/255, green: 215/255, blue: 242/255, alpha: 1.0)
        discussionBoardView.register(UITableViewCell.self, forCellReuseIdentifier: "contactCell")
        setupDiscussionBoard()

    }



    func setupDiscussionBoard() {
        view.addSubview(discussionBoardView)
        discussionBoardView.backgroundColor = UIColor(red: 203/255, green: 215/255, blue: 242/255, alpha: 1.0)
        discussionBoardView.dataSource = self
        discussionBoardView.delegate = self
        discussionBoardView.translatesAutoresizingMaskIntoConstraints = false
        discussionBoardView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        discussionBoardView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        discussionBoardView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        discussionBoardView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

}

标签: iosswiftxcode

解决方案


这是因为您尚未定义UITableViewCell 样式,并且默认情况下它使用仅包含 titleLabel 的默认样式单元格。

对于其他 UITableViewCell 样式,您必须明确指定该样式。您可以通过使用以下代码cellForRowAt:IndexPath来创建单元实例来实现此行为。

var cell: UITableViewCell
if let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: "contactCell") as? UITableViewCell {
    cell = dequeuedCell
} else {
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "contactCell")
}

这将根据您的要求输出带有 descriptionLabel 的单元格。

注意也删除以下行,您已写入viewDidLoad以注册 UITableViewCell ,因为它也使用默认样式注册 UITableViewCell ,因为它根本不需要

discussionBoardView.register(UITableViewCell.self, forCellReuseIdentifier: "contactCell")

推荐阅读