菜单
菜单

textView中字符串处理


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (NSArray *)getLinesArrayOfStringInLabel:(UITextView *)textView {
NSString *text = [textView text];
UIFont *font = [textView font];
CGRect rect = [textView 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;
}

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

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

支持一下
天若有情天亦老,请我吃糖好不好