Контроллер вида становится источником данных для табличного вида. В табличном виде есть разделы, а в каждом разделе — ячейки. Мы, в сущности, работаем с массивом массивов: массив первого порядка содержит разделы, а каждый раздел, в свою очередь, является массивом, содержащим ячейки. Отвечать за этот функционал будет элемент arrayOfSections, определяемый в заголовочном файле контроллера вида. Итак, заполним этот массив:
— (NSMutableArray *) newSectionWithIndex:(NSUInteger)paramIndex
withCellCount:(NSUInteger)paramCellCount{
NSMutableArray *result = [[NSMutableArray alloc] init];
NSUInteger counter = 0;
for (counter = 0;
counter < paramCellCount;
counter++){
[result addObject: [[NSString alloc] initWithFormat:@"Section %lu
Cell %lu",
(unsigned long)paramIndex,
(unsigned long)counter+1]];
}
return result;
}
— (NSMutableArray *) arrayOfSections{
if (_arrayOfSections == nil){
NSMutableArray *section1 = [self newSectionWithIndex:1
cellCount:3];
NSMutableArray *section2 = [self newSectionWithIndex:2
cellCount:3];
NSMutableArray *section3 = [self newSectionWithIndex:3
cellCount:3];
_arrayOfSections = [[NSMutableArray alloc] initWithArray:@[
section1,
section2,
section3
]
];
}
return _arrayOfSections;
}
Затем мы инстанцируем табличный вид и реализуем необходимые методы в протоколе UITableViewDataSource, чтобы заполнить табличный вид данными:
— (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return self.arrayOfSections.count;
}
— (NSInteger) tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section{
NSMutableArray *sectionArray = self.arrayOfSections[section];
return sectionArray.count;
}
— (UITableViewCell *) tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier
forIndexPath: indexPath];
NSMutableArray *sectionArray = self.arrayOfSections[indexPath.section];
cell.textLabel.text = sectionArray[indexPath.row];
return cell;
}
— (void)viewDidLoad{
[super viewDidLoad];
self.myTableView =
[[UITableView alloc] initWithFrame: self.view.bounds
style: UITableViewStyleGrouped];
[self.myTableView registerClass: [UITableViewCell class]
forCellReuseIdentifier: CellIdentifier];
self.myTableView.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview: self.myTableView];
}
Теперь посмотрим, что получается. Сначала проверим, как разделы перемещаются на новое место. Напишем метод, который будет перемещать раздел 1 на место раздела 3:
— (void) moveSection1ToSection3{
NSMutableArray *section1 = [self.arrayOfSections objectAtIndex:0];
[self.arrayOfSections removeObject: section1];
[self.arrayOfSections addObject: section1];
[self.myTableView moveSection:0
toSection:2];
}