我正在尝试获取一个 TableView 以将我在数组中的数据拆分为多个部分...
我对此很陌生,但下面是我的代码片段
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section == 0)
{
contentArray = [[NSArray arrayWithObjects:@"Send SMS", @"Reports", nil] retain];
}
if(section == 1)
{
contentArray = [[NSArray arrayWithObjects:@"Accounts", nil] retain];
}
return [contentArray count];
}
我已成功将数据拆分为 2 个部分,但是在填充行时,它只是在两个部分中重复第一个内容数组。
谁能帮忙...
谢谢
最佳答案
首先,您提供的代码存在漏洞。删除对 retain
的两个调用。
其次,您遇到了基于相同信息的多个开关/if..else 链的经典问题。这需要 OO 解决方案。
首先创建一个TableSection类:
@interface TableSection : NSObject
{ }
@property (nonatomic, copy) NSString* header;
@property (nonatomic, copy) NSArray* rows;
- (NSInteger)numberOfRows;
- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row;
@end
@implementation TableSection
@synthesize header;
@synthesize rows;
- (void)dealloc {
[header release];
[rows release];
[super dealloc];
}
- (NSInteger)numberOfRows {
return rows.count;
}
- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row {
// create/reuse, setup and return a UITableViewCell
}
@end
现在在你的 TableViewController 中
@interface MyViewController : UITableViewController
{ }
@property (nonatomic, retain) NSArray* tableSections;
@end
@implementation MyViewController
- (void)dealloc {
[tableSections release];
[super dealloc];
}
- (void)viewDidLoad {
TableSection* section1 = [[TableSection alloc] init];
[section1 setRows: [NSArray arrayWithObjects: @"Send SMS", @"Reports", nil]];
TableSectlion* section2 = [[TableSection alloc] init];
[section2 setRows: [NSArray arrayWithObjects: @"Accounts", nil]];
[self setTableSections: [NSArray arrayWithObjects: section1, section2, nil]];
[section2 release];
[section1 release];
}
- (void)viewDidUnload {
[self setTableSections: nil];
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView: (UITableView*)tableView {
return self.tableSections.count;
}
- (NSInteger)tableView: (UITableView*)tableView numberOfRowsInSection: (NSInteger)section {
return [[self.tableSections objectAtIndex: section] numberOfRows];
}
- (UITableViewCell*)tableView: (UITableView*)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath {
return [[self.tableSections objectAtIndex: indexPath.section] cellInTableView: tableView forRow: indexPath.row];
}
- (NSString*)tableView: (UITableView*)tableView titleForHeaderInSection: (NSInteger)section {
return [[self.tableSections objectAtIndex: section] header];
}
@end
关于iPhone TableView 数据分为 2 个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5351405/