2013-08-31 57 views
1

我希望下面的標籤(黃色)至少是兩行而不是一行。UILabel不繪製多行

problem

我確信在Interface Builder中取消選中Use Autolayout。當我將numberOfLines設置爲0到2時,我會看到兩個單詞堆疊在一起,黃色背景緊緊貼合單詞。無論lineBreakModeNSLineBreakByWordWrapping還是NSLineBreakByTruncatingTail,結果都是一樣的。如果我使用sizeWithAttributes的結果來設置術語標籤的框架,那也是一樣的,如果我使用sizeToFit也是如此。我也嘗試將標籤作爲UILabel而不是UILabel的子類,即TTTAttributedLabel,但結果是相同的。

_termsLabel.font = [UIFont systemFontOfSize:12]; 
_termsLabel.textColor = [UIColor grayColor]; 
_termsLabel.textAlignment = NSTextAlignmentCenter; 
_termsLabel.lineBreakMode = NSLineBreakByWordWrapping; 
_termsLabel.numberOfLines = 0; 
_termsLabel.delegate = self; 
_termsLabel.backgroundColor = [UIColor yellowColor]; 

// Terms label 
NSString *termsText = [NSString stringWithFormat:@"%@ %@ %@ %@", NSLocalizedString(@"TermsIAgree", nil), 
                   NSLocalizedString(@"SettingsTOS", nil), 
                   NSLocalizedString(@"LocalizedAnd", nil), 
                   NSLocalizedString(@"SettingsPrivacyPolicy", nil)]; 

_termsLabel.text = termsText; 
_termsLabel.linkAttributes = @{ (__bridge NSString *)kCTUnderlineStyleAttributeName : [NSNumber numberWithBool:YES]}; 
CGSize termsSize = [_termsLabel.text sizeWithAttributes: @{ NSFontAttributeName : _termsLabel.font}]; 
_termsLabel.frame = CGRectMake(65, 
           395, 
           termsSize.width, termsSize.height); 

[_termsLabel addLinkToURL:[NSURL URLWithString:TOS_URL] withRange:[termsText rangeOfString:NSLocalizedString(@"SettingsTOS", nil)]]; 
[_termsLabel addLinkToURL:[NSURL URLWithString:PRIVACY_POLICY_URL] withRange:[termsText rangeOfString:NSLocalizedString(@"SettingsPrivacyPolicy", nil)]]; 

編輯:通過尋找使用CGSize termsSize = [_termsLabel.text sizeWithFont:_termsLabel.font forWidth:200 lineBreakMode:NSLineBreakByWordWrapping]; 然而,條款文字大小termsSizeheight然後14,導致在短短一行:

enter image description here

我怎樣才能獲得第二線? 解決方案在這一點上,只需添加[_termsLabel sizeToFit]

+0

是否大小'termsSize'匹配標籤的大小?或者是在某個時候改變了框架? –

+0

看我的編輯。 。 。 –

回答

2

如果您有靜態文本,只需設置中斷模式進行換行,將行設置爲所需的數字,然後在界面構建器中調整標籤的框架,直到其按照您喜歡的方式進行換行。你已經有了動態文本,您可以使用sizeToFit設置標籤的文本後,系統將自動調整它的高度,以適合指定寬度:

  1. 設置幀最大所需寬度
  2. 集線至0
  3. 設置中斷模式來包裝
  4. 呼叫sizeToFit