// Objective C, - (NSUInteger)numberOfItemsInSection:(NSUInteger)section { if (self.loggedIn) { swtich (section) { case 0: return 2; case 1: { if (self.settings.showDetails) { return 5; } else { return 3; } } case 2: return 3; } } else { swtich (section) { case 1: { if (self.settings.showDetails) { return 5; } else { return 3; } } case 2: return 3; } } }
enum SectionIndex { LoginSection = 0, DetailsSection, ExtendedSection }
- (SectionIndex)sectionIndexForSection:(NSUInteger)section { if (!self.loggedIn) { ++section; } if (!self.settings.showDetails) { ++section; } return (SectionIndex)section; } - (NSUInteger)numberOfItemsInSection:(NSUInteger)section { SectionIndex sectionIndex = [self sectionIndexForSection:section]; switch (sectionIndex) { case LoginSection: return [self numberOfItemsInLoggedInSection]; case DetailsSection: return [self numberOfItemsInDetailsSection]; case ExtendedSection: return [self numberOfItemsInExtendedSection] } } }
- (NSUInteger)numberOfSections { retun [self.state numberOfSections]; } - (NSUInteger)numberOfItemsInSection:(NSUInteger)section { retun [self.state numberOfItemsInSection:section]; } - (NSString *)titleForItem:(NSUInteger)item inSection:(NSUInteger)section { retun [self.state titleForItem:item inSection:section]; } - (void)performActionForItem:(NSUInteger)item inSection:(NSUInteger)section { retun [self.state performActionForItem:item inSection:section]; }
@interface State : NSObject @property (nonatomic, strong) NSArray *sections; // ... @end @implementation State - (NSUInteger)numberOfSections { return [self.sections count]; } - (NSUInteger)numberOfItemsInSection:(NSUInteger)section { return [self.sections[section] count]; } - (NSString *)titleForItem:(NSUInteger)item inSection:(NSUInteger)section { return self.sections[section][item][@"title"]; } - (void)performActionForItem:(NSUInteger)item inSection:(NSUInteger)section { void(^actionBlock)() = self.sections[section][item][@"action"]; actionBlock(); } // - (void)setupForState { NSMutableDictionary *state = [NSMutableDictionary dictionary]; if (self.loggedIn) { [state addObject:[self loggedInSection]]; } if (self.showDetails) { [state addObject:[self detailsSection]]; } [state addObject:[self extendedSection]]; self.sections = state; } - (NSArray *)loggedInSection {...} - (NSArray *)detailsSection {...} - (NSArray *)extendedSection {...} // ...
Source: https://habr.com/ru/post/218119/
All Articles