簡體   English   中英

在UINavigationBar中動態調整字體大小

[英]Dynamically adjust font size in UINavigationBar

我想做的是這樣的:

我有一個導航欄,使用覆蓋整個欄的圖像,看起來像這樣:

在此處輸入圖片說明

現在,我想將標題放在欄的黑色部分,這樣就不會影響圖標了。 這個標題可能很短或很長。 所以我嘗試了這個:

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;

但這不起作用,因為如果需要,標簽的寬度會增加,並且超過200px。

那我該怎么辦? 謝謝你的幫助。

PS:相機圖標不是按鈕。

您的代碼在iOS 7.0中工作正常

由於您使用的是UITextAlignmentCenter(而不是NSTextAlignmentCenter),並且還使用了minimumFontSize,因此我假設您正在運行iOS的早期版本,因為這兩個版本在iOS 6.0中均已棄用

主要問題是,如果numberOfLines設置為1,則adjustsFontSizeToFitWidth僅在iOS6和更早版本中有效

如您在Apple開發人員文檔中所見

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

如果您必須要兩行並且還希望調整字體大小...,您可以只使用名稱字符串的length屬性,該屬性將告訴您字符串中有多少個字符,然后可以設置字體大小根據琴弦的長度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM