为什么在presentmodalviewcontroller调用时,navigationItem.titleView会左对齐?

Jef*_*cia 6 iphone cocoa-touch uinavigationbar ios

我正在使用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];
}
Run Code Online (Sandbox Code Playgroud)

截图: 在此输入图像描述

知道为什么会这样吗?谢谢.

Gur*_*ngh 10

我通过一些打击来调查问题并尝试找到以下事实:

  • 如果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, 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;
Run Code Online (Sandbox Code Playgroud)

现在一切都很甜蜜.yummmm.


Jef*_*cia 3

感谢 DougW 为我指明了正确的方向。这是我发现的最好的黑客。基本上我保留 UILabel 作为类属性。在呈现模式视图之前,我取消设置 titleView,然后立即重置它。当模态视图被关闭时,我取消设置然后重置 titleView。对于用户来说,这些都不是明显值得注意的。

-(void)displayComposerSheet:(NSString*)mailto 
{
    self.navigationItem.titleView = nil;
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    picker.navigationBar.tintColor = [APPDELEGATE getNavTintColor];
    [picker setToRecipients:[NSArray arrayWithObject:mailto]];
    [self presentModalViewController:picker animated:YES];
    [picker release];
    self.navigationItem.titleView = titlelabel;
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{   
    self.navigationItem.titleView = nil;
    self.navigationItem.titleView = titlelabel;
    [self dismissModalViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)