我是 iOS 开发的初学者,我很难做一些在 Web 编程中看起来很简单的事情。当 iOS 程序启动时,我运行一个函数来从我的服务器收集一些信息。在此期间,有一个 UITableView 加载了一些初始数据。大约 1 秒后,我收到服务器的响应。根据该响应,我想要么不执行任何操作,要么灰显/禁用 UITableView 中的某一行。
使用调试工具,我可以确认我的服务器请求正在工作,但在我的一生中,我无法弄清楚如何更改 UITableView 中的单元格。
这个想法是,假设服务器响应:true
,那么我想找到 UITableView 中的第一行,将文本颜色变成浅灰色并禁用触摸它。执行此操作的最佳方法是什么?
我已经尝试了很多事情,并且我不想用可能偏离目标的代码示例来解决这个问题。我可以在 UITableView 的初始加载期间做我想做的事情(使用 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
方法),但当时我仍然没有来自服务器的数据。所以对我来说最困难的部分是我需要能够在初始加载后的某个时间、每当服务器响应时对表进行这些更改。请记住,我不想更改 dataSource
的任何内容,我只想更改其中 1 行的外观/功能。
非常感谢任何帮助,谢谢!
最佳答案
您可以在 UITableViewController 中添加一个额外的变量:
var yourVar : Bool = false
然后在您从服务器接收到数据后,将变量设置为 true 或 false 并调用 reloadData():
self.yourVar = true // or self.yourVar = false
self.tableView.reloadData()
然后在您的 cellForRowAtIndexPath 函数中检查第一行以更改其外观:
if (indexPath.row == 0 && yourVar == true) {
cell.selectionStyle = UITableViewCellSelectionStyleNone
}
并且有方法willSelectRowAtIndexPath确保您不能再选择该单元格:
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return (indexPath.row == 0 && self.yourVar = true) ? nil : indexPath
}
-- 编辑--
或者,您可以使用以下方法检查 willSelectRowAtIndexPath 中单元格的选择属性:
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let cell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
return (cell.selectionStyle == UITableViewCellSelectionStyleNone) ? nil : indexPath
}
关于iOS 等待服务器数据改变 UITableView 外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36359884/