Created
December 6, 2018 08:58
-
-
Save manajay/25d182160487a31e01a134e98d1b06cb to your computer and use it in GitHub Desktop.
oc_calculate_label_text_in_single_line.codesnippest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UILabel+LSFrame.m | |
// iLawSchool | |
// | |
// Created by ljtwan on 2018/8/30. | |
// Copyright © 2018 iCourt. All rights reserved. | |
// | |
#import "UILabel+LSFrame.h" | |
#import <CoreText/CoreText.h> | |
@implementation UILabel (LSFrame) | |
- (NSUInteger)textLines { | |
return [self getLinesArrayOfString].count; | |
} | |
- (NSUInteger)maxHeight { | |
// 一行的高度 | |
self.numberOfLines = 0; | |
CGFloat labelHeight = [self sizeThatFits:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)].height; | |
return labelHeight; | |
} | |
- (NSArray *)getLinesArrayOfString { | |
NSString *text = [self text]; | |
if (!text) { | |
return @[]; | |
} | |
UIFont *font = [self font]; | |
CGRect rect = [self frame]; | |
CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL); | |
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text]; | |
[attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)]; | |
CFRelease(myFont); | |
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr); | |
CGMutablePathRef path = CGPathCreateMutable(); | |
CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000)); | |
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL); | |
NSArray *lines = ( NSArray *)CTFrameGetLines(frame); | |
NSMutableArray *linesArray = [[NSMutableArray alloc]init]; | |
for (id line in lines) { | |
CTLineRef lineRef = (__bridge CTLineRef )line; | |
CFRange lineRange = CTLineGetStringRange(lineRef); | |
NSRange range = NSMakeRange(lineRange.location, lineRange.length); | |
NSString *lineString = [text substringWithRange:range]; | |
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0])); | |
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0])); | |
[linesArray addObject:lineString]; | |
} | |
CGPathRelease(path); | |
CFRelease( frame ); | |
CFRelease(frameSetter); | |
return (NSArray *)linesArray; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment