ios - 问题获取标签中字符串的行数组

标签 ios objective-c label

我有一个字符串:“制作牙膏和漱口水的想法”。

我使用波纹管代码获取标签上的最后一个字符串。 结果字符串最后一行:“and a mouthwashg.” 但标签显示的最后一行:“牙膏和漱口水” 如何准确获取标签上的最后一行字符串? 这是我的代码:

-(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;
}

最佳答案

您可以使用 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]);

关于ios - 问题获取标签中字符串的行数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867231/

相关文章:

ios - NSNumberFormatter numberFromString 问题

ios - 用户界面没有更新,而某些功能需要时间才能执行?

ruby-on-rails - 在 Rails 中,label 和 label_tag 有什么区别?

c++ - 通过 ifdef 以编程方式确定标签是否在翻译单元中定义

ios - 同步 AVAudioPlayerNode 并开始录制 AVAudioEngine

ios - 文本字段无法输入或不显示键入的数字

ios - CloudKit 重新索引数据需要很长时间

objective-c - iOS 7.0.3 上的 "HelveticaNeue-Italic"发生了什么

iphone - iphone 应用程序的 SSL Wrapper

python - Matplotlib 绘图具有更精细的刻度线,但没有标签