ios7 新出來的根據label的文字和字體大小來確定label的寬高。
官方的方法是:
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);
其中NSStringDrawingOptions有四個枚舉值:
typedef NS_OPTIONS(NSInteger, NSStringDrawingOptions) { // 如果文本內容超出指定的矩形限制,文本將被截去并在最后一個字符后加上省略號。如果沒有指定NSStringDrawingUsesLineFragmentOrigin選項,則該選項被忽略 NSStringDrawingTruncatesLastVisibleLine = 1 << 5, // Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified. Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set. // 繪制文本時使用 line fragement origin 而不是 baseline origin NSStringDrawingUsesLineFragmentOrigin = 1 << 0, // The specified origin is the line fragment origin, not the base line origin // 計算行高時使用行距。(譯者注:字體大小+行間距=行距) NSStringDrawingUsesFontLeading = 1 << 1, // Uses the font leading for calculating line heights // 計算布局時使用圖元字形(而不是印刷字體)。 NSStringDrawingUsesDeviceMetrics = 1 << 3, // Uses image glyph bounds instead of typographic bounds} NS_ENUM_AVAILABLE_IOS(6_0);
attributes是文本字體的屬性:該參數要設置字體的大小。
context是上下文對象,用于包含信息:如何調整字間距以及縮放。最終,該對象包含的信息將用于文本繪制。該參數可為 nil。
NSDictionary *attributes1 = @{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor redColor] }; UILabel *titleLabel = [UILabel new]; titleLabel.text = @"德瑪西亞萬歲,斷劍重鑄之日,騎士歸來之時,我們要以困難的方式搞定他。我本可以打的輕一點!"; titleLabel.numberOfLines = 0;//多行顯示,計算高度 titleLabel.textColor = [UIColor blackColor]; titleLabel.backgroundColor = [UIColor greenColor]; CGSize titleSize = [titleLabel.text boundingRectWithSize:CGSizeMake(300, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes1 context:nil].size; titleLabel.frame = CGRectMake(10, 64, titleSize.width, titleSize.height); [self.view addSubview:titleLabel];
效果圖如下:
新聞熱點
疑難解答