簡體   English   中英

(快速)“ Tableview”單元格:顯示textLabel,但不顯示detailTextLabel

[英](Swift) Tableview cell: textLabel showing up, but detailTextLabel isn't

我在情節提要中設置了一個表格視圖,並為其提供了一個自定義單元格類:

故事板:

在此處輸入圖片說明

單元格類別:

class CommentCell: UITableViewCell {

override func layoutSubviews() {
    super.layoutSubviews()
    textLabel?.frame = CGRect(x: 100, y: textLabel!.frame.origin.y - 2, width: textLabel!.frame.width, height: textLabel!.frame.height)
    detailTextLabel?.frame = CGRect(x: 100, y: detailTextLabel!.frame.origin.y + 2, width: detailTextLabel!.frame.width, height: detailTextLabel!.frame.height)
}

let logoView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFit
    imageView.layer.borderWidth = 1
    imageView.layer.cornerRadius = 24
    imageView.layer.masksToBounds = true
    return imageView
}()

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)

    addSubview(logoView)
    logoView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    logoView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    logoView.widthAnchor.constraint(equalToConstant: 48).isActive = true
    logoView.heightAnchor.constraint(equalToConstant: 48).isActive = true
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

}

然后,在我的視圖控制器中,我給了它一些虛擬文本以對其進行測試,並且textLabel文本顯示得很好,但是detailTextLabel文本和imageView卻沒有。

@IBOutlet weak var tableView: UITableView!
let commentors = ["Person One", "Person Two", "Person Three"]
let comments = ["Comment One", "Comment Two", "Comment Three"]


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CommentCell

    cell.textLabel?.text = commentors[indexPath.row]
    cell.detailTextLabel?.text = comments[indexPath.row]
    DispatchQueue.main.async {
        cell.logoView.image = UIImage(named: "testImage")
    }

    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return commentors.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 72
}

這是我運行應用程序時看到的:

在此處輸入圖片說明

有人知道為什么顯示textLabel而不顯示detailTextLabel或圖像嗎?

風格的表視圖單元格custom有沒有隱含detailTextLabel並沒有imageView

您必須實現情節提要中的元素,並將它們連接到適當的IBOutlet

@vadian的答案是正確的,但是,您不必手動添加其他標簽。 我在面對您的問題時也遇到了同樣的問題,並且意識到在Interface Builder中單元格的類型是Custom而不是subtitle 您可以正確初始化它,但似乎IB中設置的樣式具有優先權。 subtitle樣式可確保detailTextLabel出現並已在情節detailTextLabel顯示。

希望這對其他人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM