textView中字符串处理


1.获取textView中每行的字符串
相关代码如下:

1
- (NSArray *)getLinesArrayOfStringInLabel:(UITextView *)textView {
2
    NSString *text = [textView text];
3
    UIFont *font = [textView font];
4
    CGRect rect = [textView bounds];
5
6
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
7
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
8
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
9
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
10
    CGMutablePathRef path = CGPathCreateMutable();
11
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
12
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
13
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
14
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
15
    for (id line in lines) {
16
        CTLineRef lineRef = (__bridge CTLineRef )line;
17
        CFRange lineRange = CTLineGetStringRange(lineRef);
18
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
19
        NSString *lineString = [text substringWithRange:range];
20
        [linesArray addObject:lineString];
21
    }
22
    return (NSArray *)linesArray;
23
}

2.按照2个英文字符作为一个字,一个中文汉字作为一个字的方式,计算字符串的实际长度
实现NSString的分类,在分类中添加方法代码:

1
//得到中英文字符串长度
2
- (NSInteger)convertToNumbers {
3
        NSInteger strlength = 0;
4
        char  *p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];
5
        for (NSInteger i = 0; i < [self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) {
6
            if (*p) {
7
                p++;
8
                strlength++;
9
            }
10
            else {
11
                p++;
12
            }
13
        }
14
        return strlength;
15
}
#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×