一聚教程网:一个值得你收藏的教程网站

热门教程

Swift中tableView单元格高度自适应的例子

时间:2022-06-25 23:34:13 编辑:袖梨 来源:一聚教程网

1,效果图
单元格内有两个文本标签,分别显示标题和内容简介。同时两个标签都是自增长的。
原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)

2,StoryBoard设置
(1)将单元格 cell 的 identifier 设置成“myCell”

原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)
 
(2)从对象库中拖入2个 Label 控件到 cell 中,分别用于显示标题和内容。
原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)
(3)并在 Attributes 面板中将两个 Label 的 Tag 值分别设置为 1 和 2,供代码中获取标签。 
原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)
(4)最后为了让两个 Label 标签能自动增长,将其 Lines 属性设置为 0。
原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)
 
3,约束设置
除了单元格 Cell 需要使用 Auto Layout 约束,单元格内的标签也要设置正确的约束,否则无法实现 Self Sizing Cells。
(1)第一个 Label(用于显示标题)设置上下左右 4 个约束。
原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)
(2)第二个 Label(用于显示内容简介)设置左右下 个约束。

原文:Swift - tableView单元格高度自适应2(自定义单元格,有2个Label标签)

例子

import UIKit
 
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
     
    var catalog = [[String]]()
     
    @IBOutlet weak var tableView: UITableView!
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //初始化列表数据
        catalog.append(["第一节:Swift 环境搭建",
            "由于Swift开发环境需要在OS X系统中运行,下面就一起来学习一下swift开发环境的搭建方法。"])
        catalog.append(["第二节:Swift 基本语法。这个标题很长很长很长。",
            "本节介绍Swift中一些常用的关键字。以及引入、注释等相关操作。"])
        catalog.append(["第三节: Swift 数据类型",
            "Swift 提供了非常丰富的数据类型,比如:Int、UInt、浮点数、布尔值、字符串、字符等等。"])
        catalog.append(["第四节: Swift 变量",
            "Swift 每个变量都指定了特定的类型,该类型决定了变量占用内存的大小。"])
        catalog.append(["第五节: Swift 可选(Optionals)类型",
            "Swift 的可选(Optional)类型,用于处理值缺失的情况。"])
         
        //创建表视图
        self.tableView.delegate = self
        self.tableView.dataSource = self
         
        //设置estimatedRowHeight属性默认值
        self.tableView.estimatedRow.0;
        //rowHeight属性设置为UITableViewAutomaticDimension
        self.tableView.rowHeight = UITableViewAutomaticDimension;
    }
     
    //在本例中,只有一个分区
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
     
    //返回表格行数(也就是返回控件数)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.catalog.count
    }
     
    //创建各单元显示内容(创建参数indexPath指定的单元)
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell",
                                        forIndexPath: indexPath) as UITableViewCell
        //获取对应的条目内容
        let entry = catalog[indexPath.row]
        let titleLabel = cell.viewWithTag(1) as! UILabel
        let subtitleLabel = cell.viewWithTag(2) as! UILabel
        titleLabel.text = entry[0]
        subtitleLabel.text = entry[1]
        return cell
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

热门栏目