作为一个学习者,我只是在玩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语句。非常感谢任何解释。
通过你的代码,一边思考“如果这是第0行怎么办”,然后“如果这是第一行怎么办”,依此类推:
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
。
这是一个典型的“边缘案例”或“一个一个”的初学者错误(通常由非创始人制作,所以不要感觉不好)。
您还可以使用开关来清理代码
switch indexPath.row {
case 0..<10:
cell.textLabel?.text = "0\(indexPath.row)"
default:
cell.textLabel?.text = "\(indexPath.row)"
}