我使用this answer中提供的代碼來創建動態標籤,並且它在大多數情況下都能正常工作。但是,只要標籤文本長度超過94個字符,它就會被截斷並省略「。動態UILabel截斷文本
還有一件更奇怪的事情是,如果我向字符串添加更多字符,它們會顯示,但最後2行仍然會被截斷。
例如,
字符串:
this is a very very long string
with lots of words to test the
dynamic bubble sizing one two three.
顯示出來是這樣的:
this is a very very long string
with lots of words to test the
dynamic bubble sizing one tw...
但是當我通過在標籤再次使用同一個句子一倍字符串時,它表現出更多的德文本,但仍將截斷它。
例如,
字符串:
this is a very very long string
with lots of words to test the
dynamic bubble sizing one two
three. this is a very very long
string with lots of words to test
the dynamic bubble sizing one
two three.
這樣表示:
this is a very very long string
with lots of words to test the
dynamic bubble sizing one two
three. this is a very very long
string with lots of words to tes...
下面是我使用的代碼。
NSString *temp = [NSString stringWithFormat:@"this is a very very long string with lots of words to test the dynamic bubble sizing one two three"];
captionLabel.text = temp;
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [temp sizeWithFont:captionLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:captionLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = captionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
captionLabel.frame = newFrame;
希望有人有一個想法,因爲這讓我撓了撓頭。
編輯
使用captionLabel.frame.size.width而不是硬編碼的296修好了,感謝@troolee,如果他/她選擇創建一個答案,我將迎來它是正確的。
看看這個! HTTP://計算器。com/questions/9059631/autoshrink-on-a-uilabel-with-multiple-lines/9060833#9060833 – 2012-07-19 10:35:23
如果您將使用captionLabel.frame.size.width而不是硬編碼的'296',該怎麼辦?也許標籤的寬度不是'296'? – 2012-07-19 10:43:06
captionLabel.frame.size.width修復了它,並將其作爲答案粘貼,並將其標記爲正確。似乎再次我已經被一些複製麪食代碼... – triggs 2012-07-19 10:46:43