作为一个学习者,我只是在玩UITableView,定制UITableViewCell,reloadData()等等来了解这些事情。
我用两个UITableViewCell创建了一个自定义UILabels。第一个应该保存一个运行号码(indexPath.row),第二个应该保存用户输入的内容。一切都很好。然后,我想它可能也只能在一个UILabel中工作,方法是从行号和内容构造一个字符串。在测试几个if语句以使单元格对齐时,我得出了如下结论:
我在cellForRowAt函数中有以下代码:
if indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7 || indexPath.row == 8 || indexPath.row == 9 {
cell.textLabel?.text = "0\(indexPath.row + 1). \(userContent[indexPath.row])"
} else if indexPath.row == 10 || indexPath.row == 11 || indexPath.row == 12 || indexPath.row == 13 || indexPath.row == 14 || indexPath.row == 15 || indexPath.row == 16 {
cell.textLabel?.text = "\(indexPath.row + 1). \(userContent[indexPath.row])"
}输出如下所示:

就像我说的:我只是在玩,这是偶然发生的。我错过了什么吗?
我只想了解为什么第10行不尊重if语句。非常感谢你的解释。
发布于 2018-04-27 15:28:04
遍历您的代码,同时思考“如果这是第0行怎么办”,然后“如果这是第1行怎么办”,等等:
if indexPath.row == 0 || indexPath.row == 1 ||
indexPath.row == 2 || indexPath.row == 3 ||
indexPath.row == 4 || indexPath.row == 5 ||
indexPath.row == 6 || indexPath.row == 7 ||
indexPath.row == 8 || indexPath.row == 9 {
cell.textLabel?.text =
"0\(indexPath.row + 1). \(userContent[indexPath.row])"
^^^^^^^^^^^^^^^^^^^^现在假设这是第9行,indexPath.row是9,所以我们使用这个分支。我们添加1,得到10,在前面加上一个0,并打印010。
这是一个典型的“边缘情况”或“逐个”初学者错误(也是非初学者经常犯的错误,所以不要感到难过)。
发布于 2018-04-28 12:17:51
您还可以使用开关来清理代码。
switch indexPath.row {
case 0..<10:
cell.textLabel?.text = "0\(indexPath.row)"
default:
cell.textLabel?.text = "\(indexPath.row)"
}https://stackoverflow.com/questions/50065624
复制相似问题