【发布时间】:2019-10-24 12:37:49
【问题描述】:
我正在学习 Swift 中的 TableView。我的老师给我这个问题:“你有20个单元格,但屏幕显示3个单元格。初始化了多少个单元格,为什么?
这是我的代码。我尝试了 20 多个单元格,它总是初始化 19 个单元格。有人可以向我解释为什么吗?非常感谢你 我在 iPhone 11 ProMax、iOS 13.1 上测试
override func viewDidLoad() {
super.viewDidLoad()
myTable.register(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "ContactCell")
myTable.dataSource = self
myTable.delegate = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as! ContactCell
cell.textLabel?.text = "Superhero"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return myTable.frame.size.height / 3.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.section)
print(indexPath.row)
}
此代码在另一个文件中
class ContactCell: UITableViewCell {
@IBOutlet weak var cellShow: UIView!
override func awakeFromNib() {
super.awakeFromNib()
print("awakeFromNib")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
【问题讨论】:
-
你怎么知道它正在初始化 19 个单元格,告诉我你在哪里看到它正在这样做。我问这个是因为你不知道它正在这样做,除非你有另一个函数来解析表格视图中的可见单元格或遍历视图树以在调试器中手动控制它们。你怎么知道是 19 岁?
-
这是因为只有适合您屏幕的单元格被初始化。证明:尝试旋转你的设备——它会更少(假设你从纵向转到横向)。
-
你可以在func awakeFormNib中看到。我在初始化单元格时打印“awakefromNib”。然后我数。如果我 retunn 100 个单元格,总是打印 19 行“awakefromNib”
-
@Kevin.D 这不是它的工作原理,这与内存中保存了多少个单元格无关。
-
我认为 LinusGeffarth 是对的。我试过 iphone 8 是 15 格,iphone 11 pro 是 17 格
标签: ios swift uitableview cell