在UINavigationBar titleView中添加2个UILabel

Ser*_*yov 1 iphone cocoa-touch objective-c uinavigationbar ios

我有一个UINavigationBar带有2行标签的自定义titleView:

        UILabel *navBarLabel = [[UILabel alloc] initWithFrame:CGRectZero];  
        UINavigationItem *item = [[UINavigationItem alloc] init];  
        navBarLabel.backgroundColor = [UIColor clearColor];
        navBarLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
        navBarLabel.numberOfLines = 2;
        navBarLabel.textAlignment = UITextAlignmentCenter;
        navBarLabel.textColor = [UIColor colorWithRed:124.0/255.f green:125.0/255.f blue:128.0/255.f alpha:1.0];
        navBarLabel.text = @"This\nis an example";
        [navBarLabel sizeToFit];
        item.titleView = navBarLabel;
Run Code Online (Sandbox Code Playgroud)

但是我没有UILabel使用2行文本,而是想添加2个UILabels,一个在另一个上面,以分别在每个"行"中实现字体的自定义.它是如何实现的?有任何想法吗?

lxt*_*lxt 7

只需创建一个父容器UIView来容纳两个标签,并使用此父容器作为标题视图.在伪代码中:

   UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
   [titleView addSubview:someLabel];
   [titleView addSubview:anotherLabel];
   item.titleView = titleView;
Run Code Online (Sandbox Code Playgroud)

...您需要确保正确设置标签框架,以便将一个标签放在另一个标签上方.你如何做到这将取决于你是否使用自动布局,但它非常简单明了.