首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >UITableView/indexPath.row:为什么if语句排除第10行?

UITableView/indexPath.row:为什么if语句排除第10行?
EN

Stack Overflow用户
提问于 2018-04-27 15:25:53
回答 2查看 181关注 0票数 1

作为一个学习者,我只是在玩UITableView,定制UITableViewCellreloadData()等等来了解这些事情。

我用两个UITableViewCell创建了一个自定义UILabels。第一个应该保存一个运行号码(indexPath.row),第二个应该保存用户输入的内容。一切都很好。然后,我想它可能也只能在一个UILabel中工作,方法是从行号和内容构造一个字符串。在测试几个if语句以使单元格对齐时,我得出了如下结论:

我在cellForRowAt函数中有以下代码:

代码语言:javascript
运行
复制
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语句。非常感谢你的解释。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-27 15:28:04

遍历您的代码,同时思考“如果这是第0行怎么办”,然后“如果这是第1行怎么办”,等等:

代码语言:javascript
运行
复制
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

这是一个典型的“边缘情况”或“逐个”初学者错误(也是非初学者经常犯的错误,所以不要感到难过)。

票数 2
EN

Stack Overflow用户

发布于 2018-04-28 12:17:51

您还可以使用开关来清理代码。

代码语言:javascript
运行
复制
switch indexPath.row {
    case 0..<10:
        cell.textLabel?.text = "0\(indexPath.row)"
    default: 
        cell.textLabel?.text = "\(indexPath.row)"

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50065624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档