最近项目需要做内容的评论,其中有要求做图文混排的处理,找了许多资料结合实际做了一些总结,这里贴出部分实现代码,希望可以帮助有需要的小伙伴。
#define BEGIN_FLAG @"["
#define END_FLAG @"]"
-(void)getImageRange:(NSString*)message : (NSMutableArray*)array {
NSRange range=[message rangeOfString: BEGIN_FLAG];
NSRange range1=[message rangeOfString: END_FLAG];
//判断当前字符串是否还有表情的标志。
if (range.length && range1.length) {
if (range.location>0) {
[array addObject:[message substringToIndex:range.location]];
[array addObject:[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)]];
NSString *str=[message substringFromIndex:range1.location+1];
[self getImageRange:str :array];
}else {
NSString *nextstr=[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)];
//排除文字是“”的
if (![nextstr isEqualToString:@""]) {
[array addObject:nextstr];
NSString *str=[message substringFromIndex:range1.location+1];
[self getImageRange:str :array];
}else {
return;
}
}
}else {
if (message != nil) {
[array addObject:message];
}
}
}
#define KFacialSizeWidth 24
#define KFacialSizeHeight 24
#define MAX_WIDTH 240
-(UIView *)assembleMessageAtIndex : (NSString *) message
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[self getImageRange:message :array];
UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
NSArray *data = array;
UIFont *fon = [UIFont systemFontOfSize:14.0f];
CGFloat upX = 0;
CGFloat upY = 0;
if (data) {
for (int i=0;i<[data count];i++) {
NSString *str=[data objectAtIndex:i];
if ([str hasPrefix: BEGIN_FLAG]&&[str hasSuffix: END_FLAG])
{
if (upX > MAX_WIDTH)
{
upY = upY + KFacialSizeHeight;
upX = 0;
}
NSString *imageName=[str substringWithRange:NSMakeRange(1, str.length - 2)];
UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
img.frame = CGRectMake(upX, upY, KFacialSizeWidth, KFacialSizeHeight);
[returnView addSubview:img];
upX=KFacialSizeWidth+upX;
} else {
for (int j = 0; j < [str length]; j++) {
NSString *temp = [str substringWithRange:NSMakeRange(j, 1)];
if (upX > MAX_WIDTH)
{
upY = upY + KFacialSizeHeight;
upX = 0;
}
CGSize size=[temp sizeWithFont:fon constrainedToSize:CGSizeMake(320, 40)];
UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(upX,upY,size.width,size.height)];
la.font = fon;
la.text = temp;
[returnView addSubview:la];
upX=upX+size.width;
}
}
}
}
returnView.frame = CGRectMake(0, 400, upX, upY); //@ 需要将该view的尺寸记下,方便以后使用
return returnView;
}