2013-02-10 47 views
9

我有UILabel,它包含兩個由新行分隔的屬性字符串。 第一個字符串的字體大小設置爲17,第二個字符的大小設置爲14. 我希望我的第一個NSMutableAttributedString的大小調整爲最小字體大小,如果其內容不能放在一行中。iOS - 使用Attributed文本自動縮小UILabel

這可能嗎?

通過在IB中爲純文本設置「自動縮小爲最小字體大小」來配置此類UILabel行爲非常簡單,但不知道如何處理屬性文本。

這裏是我的代碼:

NSString *eventName = @"Looong Event Name"; 
NSString *placeString = @"My place"; 

eventName = [eventName stringByAppendingString:@"\n"];   
NSMutableAttributedString *attrName = [[NSMutableAttributedString alloc] initWithString:eventName]; 
[attrName addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, [eventName length])]; 


NSMutableAttributedString *attrPlace = [[NSMutableAttributedString alloc] initWithString:placeString]; 
[attrPlace addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, placeString.length)]; 
[attrPlace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, placeString.length)]; 

    NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:attrName]; 
    [finalString appendAttributedString:attrPlace]; 

    UILabel *nameLabel = (UILabel *)[cell viewWithTag:100]; 

    nameLabel.attributedText = finalString; 
+0

當我嘗試這樣做時,這變成了相當頭疼的事情。我不會將此作爲答案發布,因爲可能有更好的解決方案,我無法找到。但是,我最終以編程方式配置了我的字符串的所有屬性(除了那些與大小有關的屬性),並將標籤設置爲IBOutlet,並在屬性檢查器的「Autoshrink」下拉列表中配置「Minimum Font Size」。 – 2013-02-10 14:22:32

回答

4

我想這是從你的earlier question一個遵循。

我不認爲你可以自動做到這一點,但有一個size NSAttributedString的方法,你可以用它來檢查你的字符串是否太大,如果需要調整自己。

+0

再次感謝您! :-) – Oleg 2013-02-10 14:35:07

+0

那麼你解決它奧列格? – Simon 2013-02-12 20:34:15

+0

是的,我最終使用了兩個單獨的純文本UILabels。 – Oleg 2013-10-30 12:53:21