gpt4 book ai didi

iphone - 使用indexPath.row从NSArray填充UITableView

转载 作者:行者123 更新时间:2023-11-29 04:41:42 25 4
gpt4 key购买 nike

我正在尝试填充 UITableView in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法,其中包含我在 viewDidLoad 方法中初始化的数组。

self.questionsArray = [NSArray arrayWithObjects:@"Q1",@"Q2",@"Q3",@"Q4",@"Q5",@"Q6",@"Q7",@"Q8",@"Q9",@"Q7",@"Q8",@"Q9",@"Q10",@"Q11"];

我了解如何实现各个部分并重用带有标识符的单元格。正如我见过的大多数示例一样,我尝试了 question.text = [NSString stringWithFormat:@"%d.%@", indexPath.row ,[self.questionsArray objectAtIndex:indexPath.row]];

但我越来越喜欢0. Q1      1. Q2      2. Q3      3. Q4      4. Q5      5. Q6    0. Q1      2. Q2 ....

请帮助将所有问题(NSString)加载到我的TableView中。我搞乱了indexPath.row。这很难理解。有关有效处理 indexPath 的最佳实践的任何提示。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
case 0:
return [self.questionsArray count];
case 1:
return 1;
default:
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
static NSString *QuestionCellIdentifier = @"QuestionCellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:QuestionCellIdentifier];

if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"QuestionCell" owner:self options:nil];
}
cell = questionCell; // IBoutlet
self.questionCell = nil;
}

question.text = [NSString stringWithFormat:@"%d. %@", indexPath.row ,[self.questionsArray objectAtIndex:indexPath.row]];

return cell;
}
else if (indexPath.section == 1){

static NSString *CustomCellIdentifierMore = @"CustomCellIdentifierMore";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifierMore];

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomCellIdentifierMore] autorelease];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
switch (indexPath.row) {

case 0:
cell.textLabel.text=@"Select";
break;

default:
break;
}
}

return cell;
}
return nil;
}

最佳答案

cellForRowAtIndexPath 不保证按顺序加载单元格,并且将被调用以更新某些单元格。您还需要提供 numberOfRowsInSection 方法,例如:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.tableData count];
}

您的单元格是否正确显示,还是只是 nslog 产生了令人困惑的输出?

关于iphone - 使用indexPath.row从NSArray填充UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com