ずいぶん前に、この関数を作成して、スペースとフォントを渡すと、分割された文字列が制限された幅と必要なサイズで返されます。
- (NSMutableArray *)getSplittedString:(NSString *)largeStr:(UIFont *)font:(NSInteger)horizontalSpace:(float)width {
NSArray *strWords = [largeStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//finding space width
NSInteger currIndex = 0;
NSString *tmpStr = @"";
NSString *compareStr = @"";
NSInteger currWidth;
NSMutableArray *strArray = [[NSMutableArray alloc] init];
NSMutableArray *strFrames = [[NSMutableArray alloc] init];
while(TRUE) {
while(TRUE) {
compareStr = tmpStr;
compareStr = [compareStr stringByAppendingString:[strWords objectAtIndex:currIndex]];
currWidth = [compareStr sizeWithFont:font].width;
if(currWidth < width) {
currIndex = currIndex + 1;
if(currIndex == [strWords count]) {
[strArray addObject:compareStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:compareStr :width :font :horizontalSpace]]];
break;
}
tmpStr = [NSString stringWithFormat:@"%@ ",compareStr];
} else if (currWidth == width) {
[strArray addObject:compareStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:compareStr :width :font :horizontalSpace]]];
tmpStr = @"";
if(currIndex == [strWords count]) {
break;
}
} else {
if([compareStr rangeOfString:@" "].location == NSNotFound) {
while(TRUE) {
NSInteger loc = [self findAdjustedLocation:compareStr :width :font];
if(loc == 0) {
tmpStr = [compareStr substringFromIndex:loc];
if(currIndex == [strWords count]) {
[strArray addObject:tmpStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:tmpStr :width :font :horizontalSpace]]];
break;
}
tmpStr = [NSString stringWithFormat:@"%@ ",tmpStr];
break;
} else {
tmpStr = [compareStr substringWithRange:NSMakeRange(0, loc)];
[strArray addObject:tmpStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:tmpStr :width :font :horizontalSpace]]];
tmpStr = [NSString stringWithFormat:@"%@ ",[compareStr substringFromIndex:loc]];
compareStr = tmpStr;
if ([tmpStr sizeWithFont:font].width < width) {
[strArray addObject:tmpStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:tmpStr :width :font :horizontalSpace]]];
currIndex = currIndex + 1;
break;
}
}
}
} else {
[strArray addObject:tmpStr];
[strFrames addObject:[NSValue valueWithCGRect:[self findCenterAdjustedLocation:tmpStr :width :font :horizontalSpace]]];
tmpStr = @"";
}
break;
}
}
if(currIndex == [strWords count]) {
return [[NSMutableArray alloc] initWithObjects:strArray, strFrames, nil];
break;
}
}
}