Swift-UITableView列表动态设置高度,根据不同的内容长度,设置heightForRowAt

此篇文章主要阐述如何利用swift语言,实现返回内容不同长度文本的高度,比如第一个列表文字1行,只需要50像素高度,第二个列表文字超出了1行,如2行,那么就自动调整这个单元文本的高度;

用MVC实现(view,cell,model,controller)

最终效果图如下:

一:Controller层

bash 复制代码
import UIKit

class TestController: BaseViewController {
    
    let TESTCELLCODECONTROLLER = "TESTCELLCODECONTROLLER"
    
    private var testView = TestView()
    private var dataList = [TestModel]()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        aboutNavigationCenter(title: "测试")
    }
    
    override func initView() {
        super.initView()
        testView.frame = self.view.bounds
        testView.tableView?.delegate = self
        testView.tableView?.dataSource = self
        self.view.addSubview(testView)
    }
    
    override func initData() {
        super.initData()
        dataList = TestModel.getTestModel()
        testView.tableView?.reloadData()
    }
}

extension TestController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = dataList[indexPath.row]
        let cell = TestCell(style: .default, reuseIdentifier: TESTCELLCODECONTROLLER)
        cell.configure(with: model)
        
        let width = tableView.frame.width - 20 // Adjust based on cell padding
        let textHeight = cell.textLine.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).height
        return textHeight + 90 // Add padding
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Handle cell selection
    }
}

extension TestController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: TESTCELLCODECONTROLLER) as? TestCell
        if cell == nil {
            cell = TestCell(style: .default, reuseIdentifier: TESTCELLCODECONTROLLER)
        }
        
        let model = dataList[indexPath.row]
        cell?.configure(with: model)
        
        return cell!
    }
}

二:View层

bash 复制代码
import UIKit

class TestView: BaseView {
    
    var tableView:UITableView?
    
    override func initView() {
        //主view
         tableView = UITableView()
        tableView!.separatorStyle = .none
        self.addSubview(tableView!)
        
        tableView!.snp.makeConstraints{(make)->Void in
            make.top.equalTo(self).offset(20)
            make.left.equalTo(self).offset(0)
            make.right.equalTo(self).offset(0)
            make.bottom.equalTo(self).offset(0)
        }
    }
}

三:Cell层

bash 复制代码
import UIKit
import SnapKit

class TestCell: BaseCell {
    
    var mConView: UIView?
    var textLine: UILabel!
    var additionalTextLine: UILabel! // 新的 UILabel
    var additionalTextLine2: UILabel! // 新的 UILabel
    

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        mConView = UIView()
        mConView!.layer.borderWidth = 1.0
        mConView!.layer.borderColor = UIColor.black.cgColor
        mConView!.layer.cornerRadius = 10.0
        self.contentView.addSubview(mConView!)
        
        mConView!.snp.makeConstraints { make in
            make.left.equalTo(self.contentView).offset(10)
            make.right.equalTo(self.contentView).offset(-10)
            make.top.equalTo(self.contentView).offset(10)
            make.bottom.equalTo(self.contentView).offset(-10)
        }
        
        textLine = UILabel()
        textLine.numberOfLines = 0
        textLine.lineBreakMode = .byWordWrapping
        textLine.backgroundColor = UIColor.red
        mConView!.addSubview(textLine)
        
        textLine.snp.makeConstraints { make in
            make.left.equalTo(mConView!).offset(10)
            make.top.equalTo(mConView!).offset(10)
            make.right.equalTo(mConView!).offset(-10)
        }
        
        additionalTextLine = UILabel()
        additionalTextLine.numberOfLines = 0
        additionalTextLine.lineBreakMode = .byWordWrapping
        additionalTextLine.backgroundColor = UIColor.blue // 设置不同颜色
        mConView!.addSubview(additionalTextLine)
        
        additionalTextLine.snp.makeConstraints { make in
            make.left.equalTo(mConView!).offset(10)
            make.top.equalTo(textLine.snp.bottom).offset(5) // 新文本在旧文本下方
            make.right.equalTo(mConView!).offset(-10)
        }
        
        additionalTextLine2 = UILabel()
        additionalTextLine2.backgroundColor = UIColor.yellow // 设置不同颜色
        additionalTextLine2.numberOfLines = 0
        additionalTextLine2.lineBreakMode = .byWordWrapping
        mConView!.addSubview(additionalTextLine2)
        
        additionalTextLine2.snp.makeConstraints { make in
            make.left.equalTo(mConView!).offset(10)
            make.top.equalTo(additionalTextLine.snp.bottom).offset(5) // 新文本在旧文本下方
            make.right.equalTo(mConView!).offset(-10)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(with model: TestModel) {
        textLine.text = model.lineTextModel
        additionalTextLine.text = model.additionalTextModel // 假设你在模型中有这个属性
        additionalTextLine2.text = model.additionalTextModel2
        
        textLine.sizeToFit()
        additionalTextLine.sizeToFit()
        additionalTextLine2.sizeToFit()
    }
}

四:Model层

bash 复制代码
import UIKit

class TestModel:NSObject{
    
    var lineTextModel:String?
    var additionalTextModel:String?
    var additionalTextModel2:String?
    class func getTestModel() -> [TestModel]{
        
        var array = [TestModel]()
        
        let model = TestModel()
        model.lineTextModel = "SAKDHJSAKICJFDBSJDHSCV"
        model.additionalTextModel = "我是测试1"
        model.additionalTextModel2 = "我是测试1"
        array.append(model)
        
        let model2 = TestModel()
        model2.lineTextModel = "vklmnxvlkfxklfjdjhjdsfjlvkkljvkfdjfdkjvfdkfjlklcodejdsfjlvkkljvkfdjfdkjvfdkfjlklcode"
        model2.additionalTextModel = "我是测试2"
        model2.additionalTextModel2 = "我是测试1"
        array.append(model2)
        
        let model3 = TestModel()
        model3.lineTextModel = "vfdkfjlklcodejdsfjlvkkljvkfdjfdkjvfdkfjlklcodevklmnxvlkfxklfjdjhjdsfjlvkkljvkfdjfdkjvfdkfjlklcodejdsfjlvkkljvkfdjfdkjvfdkfjlklcode"
        model3.additionalTextModel = "我是测试3"
        model3.additionalTextModel2 = "我是测试1"
        array.append(model3)
        
        return array
    }
}

复制粘贴,运行,看效果,完美!功能测试无问题,谢谢各位的阅读与关注;继续加油!

相关推荐
2401_857439692 小时前
SSM 架构下 Vue 电脑测评系统:为电脑性能评估赋能
开发语言·php
SoraLuna3 小时前
「Mac畅玩鸿蒙与硬件47」UI互动应用篇24 - 虚拟音乐控制台
开发语言·macos·ui·华为·harmonyos
xlsw_3 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
Dream_Snowar4 小时前
速通Python 第三节
开发语言·python
高山我梦口香糖5 小时前
[react]searchParams转普通对象
开发语言·前端·javascript
信号处理学渣5 小时前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客5 小时前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
jasmine s5 小时前
Pandas
开发语言·python
biomooc6 小时前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
骇客野人6 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言