Skip to content

Commit

Permalink
[Tabs] Ignore selectedItem values not in items. (#7702)
Browse files Browse the repository at this point in the history
When a client sets `selectedItem` to a value not already in `items`, the assignment should be ignored without error. This matches UITabBar's behavior.

Follow-up to #7656
  • Loading branch information
Robert Moore committed Jun 25, 2019
1 parent eadb2e1 commit cc5cce8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 17 deletions.
8 changes: 3 additions & 5 deletions components/Tabs/src/TabBarView/MDCTabBarView.m
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,10 @@ - (void)setSelectedItem:(UITabBarItem *)selectedItem {
}

NSUInteger itemIndex = [self.items indexOfObject:selectedItem];
// Don't crash, just ignore if `selectedItem` isn't present in `_items`. This is the same behavior
// as UITabBar.
if (selectedItem && (itemIndex == NSNotFound)) {
NSString *itemTitle = selectedItem.title;
NSString *exceptionMessage =
[NSString stringWithFormat:@"%@ is not a member of the tab bar's `items`.", itemTitle];
[[NSException exceptionWithName:NSInvalidArgumentException reason:exceptionMessage
userInfo:nil] raise];
return;
}

_selectedItem = selectedItem;
Expand Down
17 changes: 5 additions & 12 deletions components/Tabs/tests/unit/TabBarView/MDCTabBarViewTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -109,25 +109,18 @@ - (void)testSafelyHandlesEmptyItems {
XCTAssertNil(self.tabBarView.selectedItem);
}

// Tab bar should throw error when select the item that doesn't belongs to items.
// Tab bar should ignore setting a `selectedItem` to something not in the `items` array.
- (void)testSafelyHandlesNonExistItem {
// Given
self.tabBarView.items = @[];
XCTAssertNil(self.tabBarView.selectedItem);

// When set selected item to nil.
self.tabBarView.selectedItem = nil;

// Then should make no difference to the selection.
XCTAssertNil(self.tabBarView.selectedItem);

// Given items {A, B} which selected item A.
// When
self.tabBarView.items = @[ self.itemA, self.itemB ];
self.tabBarView.selectedItem = self.itemA;
XCTAssertEqual(self.tabBarView.selectedItem, self.itemA);
self.tabBarView.selectedItem = self.itemC;

// When set selected item to C, then should raise exception.
XCTAssertThrows(self.tabBarView.selectedItem = self.itemC);
// Then
XCTAssertNil(self.tabBarView.selectedItem);
}

// Setting items to the same set of items should change nothing.
Expand Down

0 comments on commit cc5cce8

Please sign in to comment.