I have a numberOfSections… method that looks like this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
BOOL showContacts = self.selectedReminderMessageService != RMReminderMessageServiceTwitter ? YES : NO;
if (self.isEditing) {
if (showContacts) {
return 5;
} else {
return 4;
}
} else {
if (showContacts) {
return 4;
} else {
return 3;
}
}
}
How should I create the cellForRowAtIndexPath… method? Do I have to list all possible configurations like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BOOL showContacts = self.selectedReminderMessageService != RMReminderMessageServiceTwitter ? YES : NO;
NSInteger section = [indexPath section];
if (self.isEditing) {
if (showContacts) {
if (section == 0) {
// repeat to section 4 with else if's
}
} else {
if (section == 0) {
// repeat to section 3 else if's
}
}
} else {
if (showContacts) {
if (section == 0) {
// repeat to section 3 else if's
}
} else {
if (section == 0) {
// repeat to section 2 else if's
}
}
}
}
Can this be made in a more efficient way?
So there’s an additional section that appears when isEditing is true, and an additional section that appears when showContacts is true, and these sections don’t show up if their respective condition is false. Do I have that right? Then is your question about how to make it so you have fewer
if/elses in your tableView:cellForRowAtIndexPath: method?Here’s what I’d do: First, alway return the same number of sections–5 in this case–from
numberOfSectionsInTableView. Then, intableView:numberOfRowsInSection:check the condition and return 0 when it’s false, or the appropriate number of rows if it’s true.Now, section 0 is always your “contacts” section, and section 4 is always the “add a row” section (or whatever order you want to put them in). Finally, in your
tableView:cellForRowAtIndexPath:method, you just need to check which section you’re in to make the right “type” of cell. If there are no rows in that section, then that bit of code will never be executed.If you want, you can combine this with Ismael’s idea for naming your sections, though I’ve never found the need to do more than indicate the section in comments.