设置导航栏标题的对齐方式

3

我正在尝试将应用程序导航栏标题居中对齐,但似乎标题仍停留在右侧(请查看截图)。 我正在使用以下代码:

-(void)viewDidLoad {
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStylePlain target:self action:@selector(goToHomePage:)];
    [self.navigationController.navigationItem.rightBarButtonItem setTarget:self];
    self.navigationItem.rightBarButtonItem = addButton;
    [addButton release];
}

在下面的viewWillAppear()方法中:
[self.navigationItem setTitle:offertitle];

我尝试了这个

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 120, 40)];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:14.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentLeft;
label.textColor =[UIColor whiteColor];
label.text=offertit;
self.navigationItem.titleView = label;

当我隐藏返回按钮时,标题显示居中对齐的标题。有没有办法设置返回按钮的外观属性? 图片链接在这里 请问有人可以指导我哪里错了吗?
6个回答

8

您不必使用UILabel。您可以直接使用以下代码:

[self.navigationItem setTitle:@"Your Title"];

然后你就可以开始了!这段代码将自动居中于导航栏。

或者,如果你有一个UINavigationController的实例,请使用:

[self setTitle:@"Your Title"];

我有同样的问题,但它对我没有起作用,我得到了与问题中显示的图片相同的结果。 - Arpit B Parekh

1
在前一个视图控制器的viewWillDisappear方法中,您需要设置self.title = ""。例如,从ViewControllerA打开ViewControllerB,则在ViewControllerA的“viewWillDisappear”方法中设置self.title = ""。

0
如果您有一个导航控制器,只需添加:self.title=@"您的标题";

0
尝试使用 self.navigationItem.title = @"YourTitle"; 这段代码会将标题放置在导航栏中央。

0
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // this will appear as the title in the navigation bar
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor yellowColor]; // change this color
        self.navigationItem.titleView = label;
        label.text = NSLocalizedString(@"PageThreeTitle", @"");
        [label sizeToFit];
    }

    return self;
}

0

只需在 ViewDidLoad 中调用此函数

- (void)prepareNavigationTitle
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(-50, 0.0, 240.0, 40.0)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:14.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor =[UIColor whiteColor];
    label.text=offertit;
    self.navigationItem.titleView = label;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接