Hi.

I pulled my hair way too long for this issue and finally
decided to solve the problem of the UINavigationBar's
topItem's titleView *not* being centred when either of
the other two sides had an UIBarButtonItem by ...
subclassing UINavigationBar!

All my attempts at manipulating the titleView's frame from
any place other than "layoutSubviews" have all utterly failed.

So, I just changed the UINavigationBar class reference to
UINavigationBarCenteredTitleView in IB and created:

//  UINavigationBarCenteredTitleView.h

#import <UIKit/UIKit.h>

// Hack to have the titleView centered even when there is a left 
// or right UIBarButton
@interface UINavigationBarCenteredTitleView : UINavigationBar {

}

@end

//  UINavigationBarCenteredTitleView.m

#import "UINavigationBarCenteredTitleView.h"

@implementation UINavigationBarCenteredTitleView

- (id) initWithFrame: (CGRect) frame {
    if ((self = [super initWithFrame:frame])) {
        // nothing special to do: we just override to fix
        // the layout
    }
    return self;
}

- (void) layoutSubviews {
    [super layoutSubviews] ;
    
    if (self.topItem) {
        UIView * centeredView = self.topItem.titleView ;
        
        CGRect selfFrame = self.frame ;
        CGRect viewFrame = centeredView.frame ; 
        
        viewFrame.origin.x = (selfFrame.size.width - viewFrame.size.width) / 
2.0f ;
        
        centeredView.frame = viewFrame ;
    }
}

- (void)dealloc {
    [super dealloc];
}

@end

And it works!

But ... what's wrong with this? How would I solve this problem in
a more idiomatic way?

It seems odd that I am forced to subclass just to get a
supposedly centered view ... centred, no?

Many thanks
--
JFB

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to