Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save timgcarlson/2488be29b2114a35cb06 to your computer and use it in GitHub Desktop.
Save timgcarlson/2488be29b2114a35cb06 to your computer and use it in GitHub Desktop.
Get the view of the bar button item with respect to the right most item on the navigation bar. Useful for when you want to the frame of a UIBarButtonItem on a UINavigationBar
/** Get the view of the bar button item with respect to the right most item.
@param viewsFromRight The index of the button on the navigation controller from the right side. Pass 0 if the right most view is desired.
@param navController The UINavigationController where the bar button item exists.
@returns A UIView of the item on the navigation bar provided, x number of views from the right side (where x is the viewsFromRight property.
*/
- (UIView *)barItemViewFromRight:(NSUInteger)viewsFromRight ofNavController:(UINavigationController *)navController {
UINavigationBar *navBar = navController.navigationBar;
UIView *rightView = nil;
UIView *desiredView = nil; // The right-most view to hold and eventually return
if (viewsFromRight > navBar.subviews.count) {
// There are not enough subviews on the navigation bar
return nil;
}
for (int i = 0; i <= viewsFromRight; i++) {
for (int j = 0; j < navBar.subviews.count; j++) {
UIView *v = navBar.subviews[j];
if (rightView == nil) {
rightView = v;
} else if (desiredView) {
if (v.frame.origin.x < desiredView.frame.origin.x
&& v.frame.origin.x > rightView.frame.origin.x) {
rightView = v; // The right most view
}
} else if (v.frame.origin.x > rightView.frame.origin.x) {
rightView = v;
}
}
desiredView = rightView;
rightView = nil;
}
return desiredView;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment