Don*_*yen 0 label objective-c ios
我有一个字符串:“制作牙膏和漱口水的想法”。
我使用波纹管代码来获取 label 上的最后一个字符串。结果字符串最后一行:“和漱口水”。但是标签显示的最后一行:“牙膏和漱口水”如何在标签上准确获取最后一行的字符串?这是我的代码:
-(NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label
{
NSString *text = [label text];
UIFont *font = [label font];
CGRect rect = [label bounds];
CTFontRef myFont = CTFontCreateWithName((__bridge 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)];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge 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 = (__bridge 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];
[linesArray addObject:lineString];
}
return (NSArray *)linesArray;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 NSRange 来获取您的字符串,下面的代码可以帮助您:-
NSString *strSource=@"The idea of making a toothpaste and a mouthwashg";
NSRange r1 = [strSource rangeOfString:@"toothpaste"];
NSRange r2 = [strSource rangeOfString:@"mouthwashg"];
NSRange rSub = NSMakeRange(r1.location , r2.location + r2.length - r1.location );
NSLog(@"your string:%@",[strSource substringWithRange:rSub]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
540 次 |
| 最近记录: |