首页 > 解决方案 > 原型单元格宽度超出表格视图中的页面

问题描述

编码相当新,这是我在这里的第一篇文章。我在表格视图单元中添加了一个原型单元,但是当我运行项目时,单元会跑出页面(在右侧)?有没有人可以提供任何帮助?

这是 ViewController 代码:

import UIKit

class ConsultationsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
        tableView.delegate = self
        
        ConsultationFunctions.readConsultations(completion: { [weak self] in
            self?.tableView.reloadData()
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Data.consultationModels.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ConsutationsTableViewCell
        
        cell.setup(consultationModel: Data.consultationModels[indexPath.row])
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
}

这是 TableViewController 代码:

import UIKit

class ConsutationsTableViewCell: UITableViewCell {

    @IBOutlet weak var cardView: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        cardView.layer.shadowOffset = CGSize.zero
        cardView.layer.shadowColor = UIColor.systemBlue.cgColor
        cardView.layer.cornerRadius = 10
    }
    
    func setup(consultationModel: ConsultationModel) {
        titleLabel.text = consultationModel.title
    }
}

我已经尝试尽我所能调整 Storyboards Identity、Attributes 和 Size Inspectors,但就是不明白我哪里出错了?非常感谢任何指导

标签: xcodeuitableview

解决方案


我没有在您的代码中看到接口约束,所以我猜您在 Storyboard 中有它们,或者至少应该有。

我建议您通过一些教程或指南来为cardViewtitleLabel添加新约束。这里有一个简单的:

https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/


推荐阅读