UINavigationBar多行标题

ben*_*r44 54 title uinavigationbar uinavigationcontroller uilabel uinavigationitem

是否有一种直接的方法来覆盖导航控制器中导航栏中当前导航栏项目的titleView?我已经尝试创建一个新的UIView并用我自己的UIVIew替换topView的titleView属性但没有成功.

基本上,我想要导航栏标题的多行标题.有什么建议?

pet*_*ert 83

设置titleView属性UINavigationItem.例如,在视图控制器的viewDidLoad方法中,您可以执行以下操作:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 480, 44)];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 2;
label.font = [UIFont boldSystemFontOfSize: 14.0f];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = @"This is a\nmultiline string";

self.navigationItem.titleView = label;

#if !__has_feature(objc_arc)
[label release];
#endif
Run Code Online (Sandbox Code Playgroud)

它显示如下:

多行标题栏标签

请记住,如果不是,titleView忽略该属性.leftBarButtonItemnil


sof*_*789 25

对于Swift:

let label = UILabel(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, 44))
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.text = "multiline string"
self.navigationItem.titleView = label
Run Code Online (Sandbox Code Playgroud)

对于swift 4:

    let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: 44.0))
    label.backgroundColor = UIColor.clear
    label.numberOfLines = 0
    label.textAlignment = NSTextAlignment.center
    label.text = "first line\nsecond line"
    self.navigationItem.titleView = label   
Run Code Online (Sandbox Code Playgroud)


gbk*_*gbk 23

Swift解决方案:

2行NavigationBar:

private func setupTitleView() {
    let topText = NSLocalizedString("key", comment: "")
    let bottomText = NSLocalizedString("key", comment: "")

    let titleParameters = [NSForegroundColorAttributeName : UIColor.<Color>(),
                           NSFontAttributeName : UIFont.<Font>]
    let subtitleParameters = [NSForegroundColorAttributeName : UIColor.<Color>(),
                              NSFontAttributeName : UIFont.<Font>]

    let title:NSMutableAttributedString = NSMutableAttributedString(string: topText, attributes: titleParameters)
    let subtitle:NSAttributedString = NSAttributedString(string: bottomText, attributes: subtitleParameters)

    title.appendAttributedString(NSAttributedString(string: "\n"))
    title.appendAttributedString(subtitle)

    let size = title.size()

    let width = size.width
    guard let height = navigationController?.navigationBar.frame.size.height else {return}

    let titleLabel = UILabel(frame: CGRectMake(0,0, width, height))
    titleLabel.attributedText = title
    titleLabel.numberOfLines = 0
    titleLabel.textAlignment = .Center

    navigationItem.titleView = titleLabel
}
Run Code Online (Sandbox Code Playgroud)

2行 BarButton

    let string = NSLocalizedString("key", comment: "")
    let attributes = [NSForegroundColorAttributeName : UIColor.<Color>,
                      NSFontAttributeName : UIFont.<Font>]
    let size = (string as NSString).sizeWithAttributes(attributes)
    guard let height = navigationController?.navigationBar.frame.size.height else {return}
    let button:UIButton = UIButton(frame: CGRectMake(0, 0, size.width, height))
    button.setAttributedTitle(NSAttributedString(string: string, attributes: attributes), forState: .Normal)
    button.addTarget(self, action: #selector(<SELECTOR>), forControlEvents: .TouchUpInside)
    button.titleLabel?.numberOfLines = 0
    button.titleLabel?.textAlignment = .Right
    let rightBarButton = UIBarButtonItem(customView: button)
    navigationItem.rightBarButtonItem = rightBarButton
Run Code Online (Sandbox Code Playgroud)

结果 -

在此输入图像描述


jun*_*dev 6

经过大量的调整后,我仍然无法在iOS 8中获得petert的解决方案.这是适用于iOS 8/9的复制粘贴解决方案.幸得马特·柯蒂斯的github上后

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if(!self.navigationItem.titleView){
        self.navigationItem.titleView = ({
            UILabel *titleView = [UILabel new];
            titleView.numberOfLines = 0;
            titleView.textAlignment = NSTextAlignmentCenter;
            titleView.attributedText = [[NSAttributedString alloc] initWithString:@"2\nLINES" attributes:
                self.navigationController.navigationBar.titleTextAttributes
            ];

            [titleView sizeToFit];
            // You'll need to set your frame otherwise if your line breaks aren't explcit.

            titleView;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Brainware我相信你提到的`=({});`语法是一个闭包.这些在回调函数中更常见,例如`MyClass.aFunction(x,completionHandler:{(y) - > Void in})`,但闭包实际上可用于包装任何文本,并允许包装的代码像未命名的变量或函数一样传递.Jungledev的答案使用一个闭包来包装标签创建,并在一步中将这个"块"代码传递给titleView.因此,闭包在其他语言中称为"块"或"匿名函数".请参阅:https://www.weheartswift.com/closures/. (2认同)

Voj*_*jta 5

标签未居中时该怎么办

如果您遇到与我相同的问题 - 由于后退按钮,该标签未在导航项中居中,请将您的 UILabel 嵌入到 UIView。UILabel 然后不会被迫随着它的文本增长,而是在它的宽度增加视图的宽度时停止增长。您可以在此处找到有关此问题的更多信息:无法在导航栏的中心设置 titleView 因为后退按钮(达伦的回答)

不居中:

在此处输入图片说明

- (void)setTwoLineTitle:(NSString *)titleText color:(UIColor *)color font:(UIFont *)font {
    CGFloat titleLabelWidth = [UIScreen mainScreen].bounds.size.width/2;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleLabelWidth, 44)];
    label.backgroundColor = [UIColor clearColor];
    label.numberOfLines = 2;
    label.font = font;
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = color;
    label.text = titleText;

    self.navigationItem.titleView = label;
}
Run Code Online (Sandbox Code Playgroud)

居中:

在此处输入图片说明

- (void)setTwoLineTitle:(NSString *)titleText color:(UIColor *)color font:(UIFont *)font {
    CGFloat titleLabelWidth = [UIScreen mainScreen].bounds.size.width/2;

    UIView *wrapperView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, titleLabelWidth, 44)];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleLabelWidth, 44)];
    label.backgroundColor = [UIColor clearColor];
    label.numberOfLines = 2;
    label.font = font;
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = color;
    label.text = titleText;

    [wrapperView addSubview:label];

    self.navigationItem.titleView = wrapperView;
}
Run Code Online (Sandbox Code Playgroud)