AlertViewController内嵌TableView时cellForRowAtIndexPath未调用问题
cellForRowAtIndexPath的问题 嘿,我之前也踩过这个坑!明明其他代理方法都正常触发,就是不加载cell,太闹心了。结合你的情况,给你列几个最可能的排查方向和解决办法:
先查TableView的尺寸/约束问题
AlertViewController的contentView有默认的布局限制,如果你的TableView高度设为0、约束没拉满,或者尺寸小到系统认为不需要显示内容,就会跳过cellForRowAtIndexPath的调用。
可以先手动给TableView设个固定frame测试:tableView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)如果用AutoLayout,一定要把TableView的上下左右都和Alert的view绑定,别留空或者约束错误。
确认
dataSource/delegate没被覆盖
有时候代码里写了tableView.dataSource = self,但后续某个地方不小心把它设成nil了;或者用了weak引用,导致持有对象被提前释放。可以在初始化TableView的地方打个断点,看看这两个属性的指向是否正确。强制触发TableView刷新
哪怕是静态行数,也可以在把TableView添加到Alert之后,手动调用tableView.reloadData(),确保系统收到“需要加载cell”的信号。检查
numberOfRowsInSection的方法签名
别小看低级错误!比如把方法名写成numberOfRowsInSections(多了个s),或者返回值不小心写成0了。仔细核对方法签名:func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 // 确保这里返回的是大于0的数值 }试试切换Alert的样式
如果用的是.alert样式,contentView的高度限制比较严格,换成.actionSheet样式测试一下,看看cell会不会加载——这能帮你排除Alert样式导致的布局问题。
给你贴一段我之前用过的正确嵌入代码参考:
let alertVC = UIAlertController(title: "选择内容", message: nil, preferredStyle: .alert) // 创建并配置TableView let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 250)) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell") // 添加到Alert的view中 alertVC.view.addSubview(tableView) // 设置AutoLayout约束(如果不用frame的话) tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: alertVC.view.topAnchor, constant: 70), tableView.leadingAnchor.constraint(equalTo: alertVC.view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: alertVC.view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: alertVC.view.bottomAnchor, constant: -70) ]) // 添加取消按钮 alertVC.addAction(UIAlertAction(title: "取消", style: .cancel)) present(alertVC, animated: true)
内容的提问来源于stack exchange,提问作者Abhishek Master

