Swift3中自定义UITableViewCell的contentView宽度始终为320pt求助
解决UITableViewCell初始化时contentView宽度始终为320pt的问题
嘿,太懂这种卡好几天的布局痛点了!你遇到的问题其实是UITableViewCell初始化时机的典型坑——在init(style:reuseIdentifier:)方法执行的时候,cell还没被添加到tableView中,也还没根据当前设备的屏幕尺寸完成布局计算,所以contentView的frame会停留在默认的320pt(老款iPhone的标准宽度),根本不是最终显示的实际宽度。
下面给你两个靠谱的解决方案,优先推荐第一种:
方案1:使用Auto Layout(最稳妥,适配所有场景)
放弃用frame硬写尺寸,改用Auto Layout约束来让label铺满contentView的宽度,这也是Apple推荐的布局方式,还能避免和SwipeCellKit的内部布局逻辑冲突。修改你的代码如下:
import UIKit import SwipeCellKit class ReuseableCell: SwipeTableViewCell { public var test = UILabel() var animator: Any? override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 配置label基础属性 test.text = "Lorem ipsum..." test.backgroundColor = .lightGray // 方便直观查看布局范围 test.translatesAutoresizingMaskIntoConstraints = false // 必须关闭自动转换约束 contentView.addSubview(test) // 添加约束:让label铺满contentView宽度,高度固定100,顶部对齐 NSLayoutConstraint.activate([ test.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), test.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), test.topAnchor.constraint(equalTo: contentView.topAnchor), test.heightAnchor.constraint(equalToConstant: 100) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
方案2:重写layoutSubviews(如果坚持用frame布局)
如果你因为某些原因必须用frame,那要把frame的更新逻辑放到layoutSubviews方法里——这个方法会在cell的frame确定后被调用,此时contentView的宽度就是当前设备上的实际宽度。
import UIKit import SwipeCellKit class ReuseableCell: SwipeTableViewCell { public var test = UILabel() var animator: Any? override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) test.text = "Lorem ipsum..." test.backgroundColor = .lightGray contentView.addSubview(test) } override func layoutSubviews() { super.layoutSubviews() // 此时contentView的宽度已经是正确的实际宽度 test.frame = CGRect(x: 0, y: 0, width: contentView.frame.width, height: 100) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
最后可以顺便检查下你的tableView本身是否铺满屏幕——如果tableView的宽度不是屏幕宽度,那cell的宽度也会受影响,确认下tableView的约束是否设置正确。
内容的提问来源于stack exchange,提问作者cdub
相关产品推荐
相关产品推荐

