14

I am using an external library called SwiftyWalkthrough, which allows me to expose only certain views on the screen to guide a new user through my app's UI. The first item I want exposed to the user is a UITabBarItem. I need to find the UIView associated with that specific UITabBarItem. I know the index for the item, and I have given it a tag. But I haven't found a way for them to help me find the view. Of course, I only want to use public interfaces to accomplish this.

Carl Smith
  • 1,065
  • 13
  • 18
  • There are many views in the tab bar item. which one are u looking for? – Teja Nandamuri Dec 02 '15 at 19:53
  • The one that encloses the title and icon on the tab bar at the bottom of the screen. I expect it to be rectangular, having a height identical to the entire tab bar, and a width equal to the tab bar width divided by the number of tab bar items. – Carl Smith Dec 02 '15 at 20:08
  • i think there is no access to the UITabbaritem backgroundView, we can only put the custom image for the tab bar item, but cannot get the backgroundView for the tabbar item. – Teja Nandamuri Dec 02 '15 at 20:13

3 Answers3

32

I solved my problem by accessing the subviews of the tabBar. The views with userInteractionEnabled are UITabBarItems. Sorting them by their minX values guarantees that they are in the same order as the tabBar.items array.

extension UITabBarController {
    func orderedTabBarItemViews() -> [UIView] {
        let interactionViews = tabBar.subviews.filter({$0.isUserInteractionEnabled})
    return interactionViews.sorted(by: {$0.frame.minX < $1.frame.minX})
    }
}
Nitesh
  • 1,275
  • 2
  • 18
  • 45
Carl Smith
  • 1,065
  • 13
  • 18
  • Thanks! Really nice and elegant. I know this can potentially break in the future, but there doesn't look to be a better way... – elsurudo Oct 24 '16 at 14:19
9

Swift 3 version of for Carl Smith's answer

func orderedTabBarItemViews() -> [UIView] {
    let interactionViews = tabBar.subviews.filter({$0.isUserInteractionEnabled})
    return interactionViews.sorted(by: {$0.frame.minX < $1.frame.minX})
}
Ricardo Rocha
  • 8,628
  • 9
  • 53
  • 91
Leo
  • 271
  • 3
  • 5
4

Tested in iOS10 with Objective-C:

[alert setModalPresentationStyle:UIModalPresentationPopover];

    UIView *view = [self.tabBar.selectedItem valueForKey:@"view"];

    alert.popoverPresentationController.delegate = self;
    alert.popoverPresentationController.sourceView = self.tabBar;
    alert.popoverPresentationController.sourceRect = view.frame;
    alert.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionDown;

    [self presentViewController:alert animated:YES completion:nil];
Naihmor
  • 41
  • 3