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

时间:2012-06-11 11:28:52

标签: iphone objective-c ios cocoa-touch

我正在尝试将导航栏的标题与我的应用中心对齐,但似乎标题仍然在右侧(请查看屏幕截图)。我正在使用以下代码:

-(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;

当我隐藏后退按钮时,标题会显示居中对齐的标题。是否有任何方法可以设置后退按钮的外观属性?

image link here

任何人都可以指导我可能出错的地方。

6 个答案:

答案 0 :(得分:8)

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

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

你很高兴去!此代码将自动将其自身置于导航栏的中心。

或者,如果您确实拥有UINavigationController的实例,请使用:

[self setTitle:@"Your Title"];

答案 1 :(得分:1)

您需要在上一个viewcontroller的viewWillDisappear方法中设置self.title =“”。

EG。 ViewControllerB从ViewControllerA打开,然后在ViewControllerA的“viewWillDisappear”方法中设置self.title =“”

答案 2 :(得分: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;
}

答案 3 :(得分: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;
}

答案 4 :(得分:0)

如果你有一个导航控制器,那么只需添加:self.title = @“你的标题”;

答案 5 :(得分:0)

尝试使用self.navigationItem.title = @“YourTitle”;此代码将标题放在导航栏的中心。