objective-c UITableView,我怎么知道在 cellForRowAtIndexPath 期间是哪个部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1676394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:27:44  来源:igfitidea点击:

UITableView, how do I know what Section during cellForRowAtIndexPath?

iphoneobjective-cnsmutablearray

提问by James P. Wright

I have a UITableView displaying a list of Cities. I want to separate them by State. I can't seem to figure out how to get it to pick the right items out of my Array. If Section 1 (Arizona) has 2 Cities and Section 2 (California) has 2 Cities, during cellForRowAtIndexPath, Section 2, City 1 has an index of 0, even though it's the 3rd item in my array. I thought about just turning my City Array into a State Array, where each item holds an Array of Cities, but I still don't know what section I'm on and therefore don't know which City Array under the States Array I would need to access.

我有一个显示城市列表的 UITableView。我想按州将它们分开。我似乎无法弄清楚如何让它从我的 Array 中选择正确的项目。如果第 1 节(亚利桑那州)有 2 个城市,第 2 节(加利福尼亚州)有 2 个城市,则在 cellForRowAtIndexPath 期间,第 2 节城市 1 的索引为 0,即使它是我的数组中的第 3 项。我想把我的城市阵列变成一个状态阵列,其中每个项目都包含一个城市阵列,但我仍然不知道我在哪个部分,因此不知道我会在状态阵列下哪个城市阵列需要访问。

回答by Yannick Compernol

The method is called

该方法被称为

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

The indexpath parameter contains a row and section property.

indexpath 参数包含行和节属性。

indexPath.section  
indexPath.row

Here's documentation link for the NSIndexPathclass.

这是NSIndexPath类的文档链接。

回答by Morion

you can use indexPath.sectionand indexPath.row

你可以使用indexPath.sectionindexPath.row

回答by Akbar Khan

Swift 3, 4 and 4.2

斯威夫特 3、4 和 4.2

Using Switch

使用开关

switch indexPath.section {
        case 0:
            print("Write your code for section number one.")
        case 1:
            print("Write you code for section number two")
        default:
            return
        }

Using if else

使用 if else

if indexPath.section == 0 {
            print("Write your code for section number one.")
        } else if indexPath.section == 1 {
            print("Write your code for section number two.")
        }