3

設置UILabel的屬性文本並使用setFontSizeToFitWidth時,屬性文本字體大小按預期調整大小。但是,當屬性字符串字體大小調整爲較小的字體大小時,文本不會在UILabel內部垂直對齊。垂直對齊UILabel中的屬性文本

我需要使用方法adjustFontSizeToFitWidth,因爲屬性字符串具有可變大小。我將最小字體大小設置爲「15.0」,最大字體大小設置爲「28.0」。所以我用「15.0/28.0」

我的代碼的minimumScaleFactor:

NSAttributedString *balance = [[NSAttributedString alloc] initWithString:@"12390765298374652938756" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; 

// Create UILabel with a 10.0 point padding around the UILabel within the parent Rect 
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.origin.x + 10, self.bounds.origin.y + 10, self.bounds.size.width - 20, self.bounds.size.height - 20)]; 

textLabel.attributedText = currencyWithBalance; 
textLabel.font = [UIFont fontWithName:@"TitilliumWeb-Light" size:28.0]; 
textLabel.minimumScaleFactor = 15.0/28.0; 
textLabel.textAlignment = NSTextAlignmentCenter; 
textLabel.adjustsFontSizeToFitWidth = YES; 
textLabel.numberOfLines = 1; 
textLabel.backgroundColor = [UIColor redColor]; 


[self addSubview:textLabel]; 

誰能幫助我實現這個目標,從而使文本也垂直對齊?

謝謝你們。

+0

這可能幫助你http://stackoverflow.com/questions/1054558/vertically-align-text -within-a-uilabel – iOSDeveloper

回答

1

首先,使用sizeToFit正如XCodian的評論所指出的那樣。這將確保標籤根據當前文字大小進行調整。

接下來,您需要將標籤的框架垂直放置在其容器中(在您的示例中爲self)。要做到這一點,請爲此添加一個約束,使用[UIView addConstraint:]

像這樣的東西應該被添加到您的代碼的末尾,使這項工作,大概是:

[self addConstraint: 
    [NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0] 
]; 
+0

謝謝你,偉大的解決方案! – michel