我正在使用UILabel作为导航栏的titleView(我正在制作简单的应用内网页浏览器).它工作正常,除了当我呈现模态视图控制器时,titleView从导航栏的中心移动到最左边(在后面按钮下面).我在3.0及以上测试过.这是相关代码:
- (void)viewDidLoad { [super viewDidLoad]; // Title view label CGRect labelFrame = CGRectMake(0.0,0.0,120.0,36.0); UILabel *label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease]; label.font = [UIFont boldSystemFontOfSize:14]; label.numberOfLines = 2; label.backgroundColor = [UIColor clearColor]; label.textAlignment = UITextAlignmentCenter; label.textColor = [UIColor whiteColor]; label.shadowColor = [UIColor blackColor]; label.shadowOffset = CGSizeMake(0.0,-1.0); label.lineBreakMode = UILineBreakModeMiddleTruncation; self.navigationItem.titleView = label; } -(void)displayComposerSheet:(Nsstring*)mailto { MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; [self presentModalViewController:picker animated:YES]; [picker release]; }
截图:
知道为什么会这样吗?谢谢.
解决方法
我通过一些打击来调查问题并尝试找到以下事实:
>如果UINavigationBar没有rightBarButtonItem,则titleView向右移动~30pts.
>它可以为leftBarButtonItem复制.但我没有尝试过.
在默认情况下UINavigationBar(没有更改rightBarButtonItem默认值)的情况下设置titleView.然后将新的UIView推送到导航堆栈,该导航堆栈具有rightBarButtonItem.现在,如果弹出此视图[使用后退按钮],导航栏将删除rightBarButtonItem.这将解释将titleView转移到一侧的奇怪偏移.
我如何修复问题是这样的:
self.navigationItem.titleView = myCustomTitleView; // Fake right button to align titleView properly. UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] initWithFrame:CGRectMake(0,50,1)]]; // Width equivalent to system default Done button's (which appears on pushed view in my case). rightBarButtonItem.enabled = NO; self.navigationItem.rightBarButtonItem = rightBarButtonItem;
现在一切都很甜蜜. yummmm.