UITabelView进阶
1.1动态适配cell高度(实现效果如下图)
实现原理:
tableView.estimatedRowHeight = Int//估算cell高度 tableView.AutomaticDimension //自动调整高度
1.1.1storyboard布局
实现label的约束和设置label的(Lines)显示行数为0(这样可以实现显示多行),标记lable的tag方便转化使用
1.1.2源码
import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { //这里使用的是viewController,需要手动连接和实现代理和数据源协议 var cellText = "hello world\nhello world\nhello world\nhello world\nhello world\nhello world\nhello world\n" @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //估算行高 tableView.estimatedRowHeight = 60 //自动调整行高 tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) let label = cell.contentView.viewWithTag(100) as! UILabel label.text = cellText return cell }