10

I'm trying to reposition my UIBarButtonItem so that it sits with it's edges against the top and right of the UINavigationBar. I found this accepted answer on how to do this, but I don't really understand how to code it.

I've started by creating a new class called CustomNavBar which inherits from UINavigationBar. I then placed this method in the implementation:

- (void) layoutSubviews
{


}

What I don't understand is the part in the answer that says

call [super layoutSubviews] and then find and reposition the button's view.

How do I code this? Even a nudge in the right direction would be helpful. Thanks!

Community
  • 1
  • 1
Eric Brotto
  • 53,471
  • 32
  • 129
  • 174

2 Answers2

16

Find the button you want to move after you call layoutSubviews because it will be repositioned to where iOS wants it to be every time layoutSubviews is called.

- (void) layoutSubviews
{
    [super layoutSubviews];

    for (UIView *view in self.subviews) {   // Go through all subviews
        if (view == buttonYouWant) {  // Find the button you want
            view.frame = CGRectOffset(view.frame, 0, -5);   // Move it
        }
    }
}
voidStern
  • 3,678
  • 1
  • 29
  • 32
3

You can loop through the subviews and compare if the current one is the one you want by using NSClassFromString, like this for example:

-(void)layoutSubviews {
    [super layoutSubviews];
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"TheClassNameYouWant")]) {
            // Do whatever you want with view here
        }
    }
}

You could also use NSLog in the for loop to see the different subviews.

phi
  • 10,634
  • 6
  • 53
  • 88
  • 3
    Why would you ever want to use `NSClassFromString` instead of `[TheClassNameYouWant class]`? In the latter case, you would get warnings after a refactor, which you wouldn't in the first case. – Zappel Jul 14 '15 at 05:20
  • I assume `[TheClassNameYouWant class]` should be more performant as well – yano Aug 10 '15 at 23:31