未知文本长度的动态标签框架
有时我们必须根据文本长度未知的动态内容调整 UILabel 的大小。在这个例子中,UILabel 的宽度固定为 280 点,高度是无限的,比方说 9999.估计相对于文本样式和 maximumLabelSize 的帧。
Objective-C 的
UILabel * label = [[UILabel alloc] init];
NSString *message = @"Some dynamic text for label";
//set the text and style if any.
label.text = message;
label.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(280, 9999); //280:max width of label and 9999-max height of label.
// use font information from the UILabel to calculate the size
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
//Deprecated in iOS 7.0
//CGSize expectedLabelSize = [message sizeWithFont:label.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
// create a frame that is filled with the UILabel frame data
CGRect newFrame = label.frame;
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height;
// put calculated frame into UILabel frame
label.frame = newFrame;
迅速
var message: String = "Some dynamic text for label"
//set the text and style if any.
label.text = message
label.numberOfLines = 0
var maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
var expectedLabelSize: CGSize = label.sizeThatFits(maximumLabelSize)
// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = label.frame
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height
// put calculated frame into UILabel frame
label.frame = newFrame