我使用以下兩種方法(一種是NSString
的類別,另一種是UILabel
的類別)根據其中的文本自動調整標籤的高度。它的大部分工作正常,但它有一些不可預知的結果。我不太確定問題的發生位置,我希望你們中的一些人能夠提供幫助。首先,這裏是有問題的方法:自動調整UILabel的高度
NSString的類別:
- (CGFloat) fontSizeWithFont: (UIFont *) font constrainedToSize: (CGSize) size minimumFontSize: (CGFloat) minimumFontSize
{
CGFloat fontSize = [font pointSize];
CGFloat height = [self sizeWithFont: font constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
UIFont *newFont = font;
// Reduce font size while too large, break if no height (empty string)
while (height > size.height && height != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
height = [self sizeWithFont: newFont constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
};
// Loop through words in string and resize to fit
for (NSString *word in [self componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
CGFloat width = [word sizeWithFont: newFont].width;
while (width > size.width && width != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
width = [word sizeWithFont: newFont].width;
}
}
return fontSize;
}
的UILabel類別:
- (void) sizeToFitMultipleLines
{
if (self.adjustsFontSizeToFitWidth) {
CGFloat adjustedFontSize = [self.text fontSizeWithFont: self.font constrainedToSize: self.frame.size minimumFontSize: self.minimumScaleFactor];
self.font = [self.font fontWithSize: adjustedFontSize];
}
[self sizeToFit];
}
多數民衆贊成中出現的問題是,標籤所具有的高度它的頂部和底部是空的空間,並且它內部的字符串越長,空間就越大。單行標籤可能在標籤的框架內上下可能有10個像素,但六行字符串可能有近100個像素。我無法追蹤這些額外空間來自上述方法的位置。
其次,有時會調整標籤的寬度,我只希望改變高度。我猜[self sizeToFit]
是什麼導致這個特定的問題,但我不完全確定,因爲如果我刪除它的高度仍然未調整。 編輯:我已經解決了這個寬度的問題,通過手動重新定位標籤後,其大小適合(其X座標是現在的屏幕寬度減去標籤寬度,除以2)。
有什麼想法?如果您需要更多信息或代碼,請詢問。在我對有問題的標籤調用[sizeToFitMultipleLines]
方法之前,我總是設置字體,所以這不是問題。
我用的這個變化得到它的工作。問題實際上是這個標籤和另一個標籤之間的距離,而不是標籤設置錯誤。 – Luke 2013-03-07 14:27:46