1

我迷路了。我搜索并搜索,找不到我的自定义单元格未显示的原因。

//  ProfileCell.swift:

import UIKit
import QuartzCore

class ProfileCell: UITableViewCell {

    @IBOutlet weak var profileNameLabel:    UILabel!
    @IBOutlet weak var profilePictureView:  UIImageView!
}

第二个默认的 TableViewCell 正常显示。我在 Interface Builder 中没有缺少约束或任何错误。ProfileCell 在 ProfileCell.xib 标识选项卡中选择为自定义类。

//  MoreTableViewControllerIB.swift

import UIKit

class MoreTableViewControllerIB: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {       
    return 2
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //  this cell is missing
        if indexPath.row == 0 {

            tableView.register(UINib(nibName: "ProfileCell", bundle: nil), forCellReuseIdentifier: "ProfileCell")
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) as! ProfileCell            
            cell.profileCommentLabel.text = "Test Comment Label"
            cell.profilePictureView.image = UIImage(named:"profile_picture_test")            
            return cell

        // this cell is displayed perfectly
        }else if indexPath.row == 1 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "statisticsCell") ?? UITableViewCell(style: .default, reuseIdentifier: "statisticsCell")
            cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
            cell.textLabel?.text = "Statistics"
            cell.imageView.image = UIImage(named:"statistics")
            return cell

        // has to return a cell in every scenario
        }else{
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
            return cell
        }
    }
}

这是我得到的截图。

4

3 回答 3

6
tableView.register(UINib(nibName: "ProfileCell", bundle: nil), forCellReuseIdentifier: "ProfileCell")

在 viewDidLoad 或 viewWillApppear 添加这一行

于 2017-06-12T04:30:30.333 回答
0

就我而言,我必须另外注册 nib 以查看我的单元格:

myTableView.register(UINib(nibName: "nibwithcell", bundle: nil), forCellReuseIdentifier: "cell") // you need to register xib file
于 2021-03-25T19:45:21.990 回答
0

所以我发现我的错误是什么。非常愚蠢,花了我半天时间:

单元格已显示,但默认高度不足以看到它。我认为将使用 .xib 中的设置高度。显然不是。所以我添加了这个:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 192 // the height for custom cell 0
    }
}
于 2017-06-13T19:49:21.040 回答