Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions SNFSegmentedViewController/SNFSegmentedViewController.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@

#import <UIKit/UIKit.h>

/**
* SNFSegmentedViewController is the simplest way to use a UISegmentedControl to switch between view controllers.
* Just set the view controllers property in code or in a storyboard.
* The UIViewController's title is used for the segmented control. If the title is nil, an empty string is used instead.
*/
@interface SNFSegmentedViewController : UITabBarController

@property (strong, nonatomic, readonly) UISegmentedControl *segmentedControl;
Expand Down
26 changes: 22 additions & 4 deletions SNFSegmentedViewController/SNFSegmentedViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ - (void)viewWillAppear:(BOOL)animated {

#pragma mark - IB Action

- (IBAction)segmentTapped:(UISegmentedControl *)sender {
- (void)segmentTapped:(UISegmentedControl *)sender {
self.selectedIndex = sender.selectedSegmentIndex;
}

Expand All @@ -57,10 +57,10 @@ - (IBAction)segmentTapped:(UISegmentedControl *)sender {
- (void)configureForInitialization {
self.delegate = self;

NSMutableArray *titles = [NSMutableArray arrayWithCapacity:[self.tabBar.items count]];
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:self.tabBar.items.count];
for (UITabBarItem *tabBarItem in self.tabBar.items) {
[titles addObject:tabBarItem.title];
[titles addObject:tabBarItem.title ?: @""];
}

_segmentedControl = [[UISegmentedControl alloc] initWithItems:[titles copy]];
Expand Down Expand Up @@ -91,4 +91,22 @@ - (void)hideTabBar {

}

#pragma mark - UITabBarController overrides

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
[super setSelectedIndex:selectedIndex];
self.segmentedControl.selectedSegmentIndex = selectedIndex;
}

- (void)setSelectedViewController:(UIViewController *)selectedViewController {
[super setSelectedViewController:selectedViewController];
self.segmentedControl.selectedSegmentIndex = [self.viewControllers indexOfObject:selectedViewController];
}

//setViewControllers funnels to this method so we do not need to override that method.
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated {
[super setViewControllers:viewControllers animated:animated];
[self configureForInitialization];
}

@end