简体   繁体   English

在UINavigationBar中动态调整字体大小

[英]Dynamically adjust font size in UINavigationBar

What I want to do is this : 我想做的是这样的:

I've a navigation bar using an image covering the whole bar and looking like this: 我有一个导航栏,使用覆盖整个栏的图像,看起来像这样:

在此处输入图片说明

Now I want to put the title on the black part of the bar and so it doesn't impinge on the icon. 现在,我想将标题放在栏的黑色部分,这样就不会影响图标了。 This title may be very short or very long. 这个标题可能很短或很长。 So I tried this: 所以我尝试了这个:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
label.backgroundColor = [UIColor blackColor];
label.numberOfLines = 2;
label.minimumFontSize = 8.;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont boldSystemFontOfSize:16.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor =[UIColor whiteColor];
label.text = name;
self.navigationItem.titleView = label;

But this is not working because the label's width grows if needed upon the label and exceeds 200px. 但这不起作用,因为如果需要,标签的宽度会增加,并且超过200px。

What should I do then? 那我该怎么办? Thanks for your help. 谢谢你的帮助。

PS : the camera icon is not a button. PS:相机图标不是按钮。

Your code works fine in iOS 7.0 您的代码在iOS 7.0中工作正常

Since you are using UITextAlignmentCenter (instead of NSTextAlignmentCenter), and also using minimumFontSize, I am assuming you are running on an earlier version of iOS, since these were both deprecated in iOS 6.0 由于您使用的是UITextAlignmentCenter(而不是NSTextAlignmentCenter),并且还使用了minimumFontSize,因此我假设您正在运行iOS的早期版本,因为这两个版本在iOS 6.0中均已弃用

The main problem is that adjustsFontSizeToFitWidth only works in iOS6 and earlier if the numberOfLines is set to 1 主要问题是,如果numberOfLines设置为1,则adjustsFontSizeToFitWidth仅在iOS6和更早版本中有效

As you can see in the apple developer documentation 如您在Apple开发人员文档中所见

https://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth https://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth

If you necessarily want two lines and also want the font size to adjust... you could maybe just use the length property of your name string, which would tell you how many characters are in the string, and you could then set the font size according to the length of the string 如果您必须要两行并且还希望调整字体大小...,您可以只使用名称字符串的length属性,该属性将告诉您字符串中有多少个字符,然后可以设置字体大小根据琴弦的长度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM