导航栏标题对齐

时间:2016-04-26 07:01:28

标签: ios objective-c xcode uinavigationcontroller

enter image description here

[[UIBarButtonItem appearance] 

    setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTitleTextAttributes:
         @{NSForegroundColorAttributeName:RED_COLOR ,NSFontAttributeName:[UIFont fontWithName:@"OpenSans-Semibold" size:16]}];
        self.navigationItem.title=@"ORDER DETAILS";

我使用上面的代码为视图控制器设置标题,但标题不正确。在某些视图控制器中,它按预期进行

2 个答案:

答案 0 :(得分:1)

  // here to create a UILabel

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blackColor];
    label.numberOfLines = 1;
// set your custom font for title

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"ORDER DETAILS"];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:NSMakeRange(0,5)];

// set line spacing
    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
    [paragrahStyle setLineSpacing:6];
    [paragrahStyle setAlignment:NSTextAlignmentCenter];
    [string addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [string length])];

    label.attributedText = string;
    [label sizeToFit];
    self.navigationItem.titleView = label;

复制自:Navigationbar title alignment issue

或者更好的想法是将标题作为UiImage,你可以将该图像用作导航栏标题。使用尺寸合适的44x44 pt图像,2x和3x版本。

UIImageView* titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Orderpng.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;

UIView* titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
imageView.frame = titleView.bounds;
[titleView addSubview:imageView];

self.navigationItem.titleView = titleView;

享受编码:)

答案 1 :(得分:0)

对于任何寻找Xamarin解决方案的人:

var label = new UILabel();
            label.Text = title;
            label.Font = UIFont.FromName(Strings.OpenSans_Bold, 30f);//This is a custom font. You will have to add it to your project first.
            label.TextAlignment = UITextAlignment.Left;
            label.SizeToFit();
            NavigationController.NavigationBar.TopItem.LeftBarButtonItem = new UIBarButtonItem(label);