最像iPhone的表单界面将是分组表视图。在使用其他应用程序添加和编辑结构化数据时,大多数用户都会期望这种界面。
一个好的实践是为各个部分和各个部分中的行创建一个枚举(enum
),例如:
typedef enum {
kFormSectionFirstSection = 0,
kFormSectionSecondSection,
kFormSectionThirdSection,
kFormSections
} FormSection;
typedef enum {
kFormFirstSectionFirstRow = 0,
kFormFirstSectionSecondRow,
kFormFirstSectionRows
} FormFirstSectionRow;
...
在这个例子中,您可以使用这个枚举来通过名称而不是数字来引用部分。
(实际上,您可能不会使用“kFormSectionFirstSection”作为描述性名称,而是像“kFormSectionNameFieldSection”或“kFormSectionAddressFieldSection”等类似的名称,但这应该能说明“enum”的结构。)
您该如何使用它?
以下是一些表视图委托方法的示例,演示了如何使用此功能:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return kFormSections;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch (section) {
case kFormSectionFirstSection:
return kFormFirstSectionRows;
case kFormSectionSectionSection:
return kFormSecondSectionRows;
...
default:
break;
}
return -1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.section) {
case kFormSectionThirdSection: {
switch (indexPath.row) {
case kFormThirdSectionFourthRow: {
break;
}
default:
break;
}
}
default:
break;
}
return cell;
}
这将快速展示枚举的实用性和强大性。
在代码中使用名称比数字更易于阅读。当您处理委托方法时,如果对于一个部分或行有一个良好的描述性名称,您可以更容易地阅读表视图和单元格的管理逻辑。
如果您想要更改部分或行的顺序,您只需要重新排列enum
结构中枚举标签的顺序即可。您不需要进入所有委托方法并更改魔法数字,一旦您有超过几个部分和行,这很快就会变得棘手和容易出错。
-(void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:
来滚动当前字段,使其在键盘显示时处于最佳位置。 - jamone