自动计算高度支持系统autolayout搭建的cell(xib以及snapkit等基于autolayout的约束框架都是支持的)
理论上这个框架里取cell缓存的高度的命中率是100%,性能应该还不错
效果:
IMG_3910.PNG实现步骤:
1、搭建cell
我这里是用xib搭建的cell(注:cell需要继承ZJTableViewCell类),正常拖即可,但是注意的是加的约束要填满cell。比如我截图的cell中这三处的约束加上两个cell自身的高度,就填满了cell高度,就可以计算出cell的高度了。
image.png
class AutomaticHeightCellItem: ZJTableViewItem {
var title: String!
var content: String!
}
/// 动态高度的cell说明:支持系统autolayout搭建的cell(xib以及snapkit等基于autolayout的约束框架理论上都是支持的)
class AutomaticHeightCell: ZJTableViewCell {
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelContent: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
/// cell即将出现在屏幕中的回调方法 在这个方法里面赋值
override func cellWillAppear() {
let item = self.item as! AutomaticHeightCellItem
labelTitle.text = item.title
labelContent.text = item.content
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
3、计算高度
class AutomaticHeightViewController: UIViewController {
var tableView: UITableView!
var manager: ZJTableViewManager!
override func viewDidLoad() {
super.viewDidLoad()
title = "AutomaticHeight"
self.tableView = UITableView(frame: self.view.bounds, style: .grouped)
self.view.addSubview(self.tableView);
self.manager = ZJTableViewManager(tableView: self.tableView)
self.manager.register(AutomaticHeightCell.self, AutomaticHeightCellItem.self)
let section = ZJTableViewSection(headerTitle: "Section")
manager.add(section: section)
var datas = [[String:String]]()
for _ in 0..<50 {
//注: randomStr()是随机产生字符串的方法
datas.append(["title":randomStr(), "content":randomStr(), "right":randomStr()])
}
for data in datas {
let item = AutomaticHeightCellItem()
item.title = data["title"]
item.content = data["content"]
//计算高度
item.autoHeight(manager)
section.add(item: item)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//随机产生不确定长度字符串
func randomStr() -> String{
let random_str_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var ranStr = ""
let len = arc4random_uniform(100)
for _ in 0..<len {
let index = Int(arc4random_uniform(UInt32(random_str_characters.count)))
ranStr.append(random_str_characters[random_str_characters.index(random_str_characters.startIndex, offsetBy: index)])
}
return ranStr
}
}
demo地址:
TableViewManager
码字不易,顺手star是美德:)
网友评论