投稿文章,作者:MangoMade( 简书 )
tableView再常见不过了,现在的项目中基本上都会用到很多tableView。并且很多时候tableView上每一行的内容都不同。
一个展现用户信息的页面,有的cell最右侧是图片,有的cell最右侧显示的是文本(名字、手机号、性别、余额)
一个填写用户信息的列表,有各种各样的textField
tableViewCell的数量有限,并且数量不大。不需要重用cell也能搞定。
比起写出多个cell子类去适应这些情况,不如把这些label或者textfield作为viewControler的熟悉,在tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)代理方法中把这些特定控件加到cell上,修改或者获取这些控件时非常方便。
注册多种cell很麻烦,在这种情况下很多余。
很多人应该遇到过的情况,重用cell会让视图变得很混乱,一些图片或空间因为重用的出现在了不该出现的地方
在storyBoard中可以设置static cell,来关闭重用。可是如果tableView是用代码建立的,就没有某个系统库的方法能够设置static cell。
于是在swift下我写了一个简单的extension可以实现关闭重用的效果。实现原理也非常简单,show code:
extension UITableView { /* 弹出一个静态的cell,无须注册重用,例如: let cell: GrayLineTableViewCell = tableView.mm_dequeueStaticCell(indexPath) 即可返回一个类型为GrayLineTableViewCell的对象 - parameter indexPath: cell对应的indexPath - returns: 该indexPath对应的cell */ func mm_dequeueStaticCell (indexPath: NSIndexPath) -> T { let reuseIdentifier = "staticCellReuseIdentifier - /(indexPath.description)" if let cell = self.dequeueReusableCellWithIdentifier(reuseIdentifier) as? T { return cell }else { let cell = T(style: .Default, reuseIdentifier: reuseIdentifier) return cell } } } 无须注册。
将cell直接声明为其需要的类型,改方法会自动返回这个类型的cell。
泛型函数的调用必须是以下写法:
let cell: GrayLineTableViewCell = tableView.mm_dequeueStaticCell(indexPath)
如果写成:
let cell = tableView.mm_dequeueStaticCell(indexPath)
将会报错,这种写法只适用于 泛型类型,不适用于 泛型函数