ios - UITableView/indexPath.row : why does if statement exclude row 10?

标签 ios swift uitableview

作为一名学习者,我只是在玩弄 UITableView、自定义 UITableViewCellreloadData() 以及所有这些来了解这些东西。

我创建了一个带有两个 UILabels 的自定义 UITableViewCell。第一个应该包含一个流水号 (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])"

        }

输出看起来像这样:

Entry 10 has a leading 0 although I told it not to have

正如我所说:我只是在玩,这只是偶然发生的。我在这里错过了什么吗?

我只是想了解为什么第 10 行不尊重 if 语句。 非常感谢任何解释。

最佳答案

遍历您的代码,同时思考“如果这是第 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

这是典型的“边缘案例”或“偏离一个”的初学者错误(也经常由非初学者犯下,所以不要难过)。

关于ios - UITableView/indexPath.row : why does if statement exclude row 10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065624/

相关文章:

swift - 在 Swift 中将闭包存储为变量

ios - TableView 导航到 View Controller 和其他单元格中的其他操作

ios - UICollectionViewController 中的 Flipped CollectionView 被 Navigation Controller 覆盖

ios - UITableViewCell 附件复选标记在单元格上重复

ios - 如何使用 Swift 以编程方式添加约束

iOS for Android View.GONE setVisibility 模式

ios - 如何避免 subview Controller 的内存泄漏

Swift 3 UITableView 部分显示在列表后面

ios - XCode 5.1 强制对 Cocos2d-iphone v3 项目进行 32 位编译

ios - 如何识别或匹配两张图片?