本文主要是介绍通过RTLabel、RCLabel、FTCoreText及webView结合SDWebImage等4种方式实现左滑或下拉中cell中图文混排使用场景方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.RTLabel和RCLabel两个在使用方式上差不多,对服务端吐的的数据要求比较高
json数据最好是定制式
{"type","img",con:"http://www.xxx.com/123.png", “width":"300", "height":"300"}
{"type","text",con:"图片名称", “width":"", "height":""}
类似这种方式去对cell中的每一项进行遍历显,部分代码实例如下:
导入RTLabel
#import "RTLabel.h"
在UITableViewCell中实现如下代码
- - (void)layoutSubviews
- {
- [super layoutSubviews];
- CGSize optimumSize = [self.rtLabel optimumSize];
- CGRect frame = [self.rtLabel frame];
- frame.size.height = (int)optimumSize.height+20; // +5 to fix height issue, this should be automatically fixed in iOS5
- [self.rtLabel setFrame:frame];
- }
/**
* 初始化
*/
- - (void)setupView{
- //没有分隔线
- self.selectionStyle = UITableViewCellSeparatorStyleNone;
- self.backgroundColor = [UIColor clearColor];
- self.contentView.backgroundColor = [UIColor clearColor];
- self.rtLabel = [PostTextCell textLabel];
- self.rtLabel.userInteractionEnabled = YES;
- self.rtLabel.delegate = self;
- [self.contentView addSubview:self.rtLabel];
- }
/**
* 设置内容样式
*/
- + (RTLabel*)textLabel
- {
- RTLabel *rtLabel = [[RTLabel alloc] initWithFrame:CGRectMake(10,0,300,100)];
- rtLabel.backgroundColor = [UIColor clearColor];
- rtLabel.lineBreakMode = NSLineBreakByWordWrapping;
- rtLabel.textColor = [[UIColor alloc]initWithRed:50.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:1.0f];
- rtLabel.font = [UIFont systemFontOfSize:16];
- rtLabel.linkAttributes = [NSDictionary dictionaryWithObject:@"#4595CB" forKey:@"color"];
- rtLabel.selectedLinkAttributes = [NSDictionary dictionaryWithObject:@"#4595CB" forKey:@"color"]; //BEBEBE
- //rtLabel.selectedLinkAttributes = [NSDictionary dictionaryWithObject:@"#darkGray" forKey:@"color"];
- rtLabel.textAlignment = NSTextAlignmentLeft;
- [rtLabel setParagraphReplacement:@""];
- return rtLabel;
- }
- /**
- * 获取内容高度
- */
- + (float)getHeightWithData:(NSString *)aData{
- RTLabel *rtLabel = [PostTextCell textLabel];
- [rtLabel setText:[NSString stringWithFormat:@"%@",aData]];
- CGSize optimumSize = [rtLabel optimumSize];
- return optimumSize.height+10;
- }
另一种RCLabel的实现方式和RTLabel方法基本一样,当遇到图片时
最好单起图片的cell用SDWebImage显示即可,代码如下:
#import "ImgCell.h"
- /**
- * 图片cell视图初始化
- */
- - (void)setupView{
- //没有选择效果
- self.selectionStyle = UITableViewCellSeparatorStyleNone;
- self.backgroundColor = [UIColor clearColor];
- self.contentView.backgroundColor = [UIColor clearColor];
- //图片展示
- _imgView = [[JzbNetImageView alloc] initWithFrame:CGRectMake(10, IMGVIWE_TOP, IMGVIEW_WIDTH, IMGVIEW_HEIGHT)];
- [self.contentView addSubview:_imgView];
- _imgView.userInteractionEnabled = YES;
- //加点击处理
- _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapInImgView:)];
- [_imgView addGestureRecognizer:_tapGesture];
- }
/**
* 下载图片并按比例缩放
*/
- - (NSString *)updateImgCellWithItem:(Item *)aItem pushViewController:(id)viewController
- {
- _postItem = aItem;
- _pushViewController = viewController;
- NSString *imgURL;
- //图片展示(图片宽高进行处理)
- if (aItem.width>0 && aItem.height>0) {
- /** 获取图片等比例缩放值 **/
- CGSize size = [self scaleSize:aItem.width aHeight:aItem.height];
- _imgView.frame = CGRectMake((FD_SCREEN_MAIN_WIDTH-size.width)/2, IMGVIWE_TOP, size.width, size.height);
- imgURL = [NSObject JzbGetAttachImgAttachID:aItem.atthID postID:aItem.threadID width:size.width height:size.height];
- }else{
- _imgView.frame = CGRectMake(10, IMGVIWE_TOP, IMGVIEW_WIDTH, IMGVIEW_HEIGHT);
- imgURL = [NSObject JzbGetAttachImgAttachID:aItem.atthID postID:aItem.threadID width:300 height:0];
- }
- SDWebImageManager *manager = [SDWebImageManager sharedManager];
- [manager downloadImageWithURL:[NSURL URLWithString:imgURL]
- options:SDWebImageRefreshCached
- progress:nil
- completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
- if (finished && [error code]>=0) {
- _imgView.image = image;
- _errorCode = NO;
- _imgView.userInteractionEnabled = YES;
- }else{
- _imgView.image = [UIImage imageNamed:@"bg_img_loading.png"];
- _errorCode = YES;
- _imgView.userInteractionEnabled = NO;
- }
- }];
- return imgURL;
- }
- /**
- * 图片等比例缩放
- */
- - (CGSize)scaleSize:(NSInteger)aWidth aHeight:(NSInteger)aHeight
- {
- int h = aHeight;
- int w = aWidth;
- CGSize _size;
- if(h <= (FD_SCREEN_MAIN_HEIGHT-20) && w <= (FD_SCREEN_MAIN_WIDTH-20)){
- _size = CGSizeMake(w, h);
- }else{
- float b = (float)(FD_SCREEN_MAIN_WIDTH-20)/w < (float)(FD_SCREEN_MAIN_HEIGHT-20)/h? (float)(FD_SCREEN_MAIN_WIDTH-20)/w : (float)(FD_SCREEN_MAIN_HEIGHT-20)/h;
- _size = CGSizeMake(b*w, b*h);
- }
- return _size;
- }
- /**
- * 大图显示
- */
- - (void)tapInImgView:(id)sender{
- NSString *imgUrl;
- if ([_postItem.con hasPrefix:@"http"]) {
- imgUrl = _postItem.con;
- }else{
- imgUrl = [NSObject SDGetAttachImgAttachID:_postItem.atthID postID:_postItem.threadID];
- }
- if (imgUrl.length > 0 && _errorCode == NO) {
- FullScreenImageView *fullView = [[FullScreenImageView alloc] initWithImage:_imgView.image inFrame:self.window.bounds withThumbnailImageFrame:[_imgView convertRect:_imgView.bounds toView:self.window] andOriginUrl:[NSURL URLWithString:imgUrl]];
- [self.window addSubview:fullView];
- [UIApplication sharedApplication].statusBarHidden = YES;
- }
- }
通过以上代码实现可以实现以下效果:
2.FTCoreText相对RTLabel和RCLabel相对新一些,能对复杂的Json格式中数据项进行定制
像类似下图这样交果就比较灵活,部分代码实例如下
- /**
- * 初始化
- */
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
- scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
- coreTextView = [[FTCoreTextView alloc] initWithFrame:CGRectMake(20, 20, 280, 0)];
- coreTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
- //设置内容
- [coreTextView setText:[self textForView]];
- //设置样式
- [coreTextView addStyles:[self coreTextStyle]];
- //设置代理
- [coreTextView setDelegate:self];
- //设置内容和高度
- [coreTextView fitToSuggestedHeight];
- [scrollView addSubview:coreTextView];
- [scrollView setContentSize:CGSizeMake(CGRectGetWidth(scrollView.bounds), CGRectGetHeight(coreTextView.frame) + 40)];
- [self.view addSubview:scrollView];
- }
- /**
- * 设置html中的内容样式
- */
- - (NSArray *)coreTextStyle
- {
- NSMutableArray *result = [NSMutableArray array];
- FTCoreTextStyle *defaultStyle = [FTCoreTextStyle new];
- defaultStyle.name = FTCoreTextTagDefault; //thought the default name is already set to FTCoreTextTagDefault
- defaultStyle.font = [UIFont fontWithName:@"TimesNewRomanPSMT" size:16.f];
- defaultStyle.textAlignment = FTCoreTextAlignementJustified;
- [result addObject:defaultStyle];
- FTCoreTextStyle *titleStyle = [FTCoreTextStyle styleWithName:@"title"]; // using fast method
- titleStyle.font = [UIFont fontWithName:@"TimesNewRomanPSMT" size:40.f];
- titleStyle.paragraphInset = UIEdgeInsetsMake(0, 0, 25, 0);
- titleStyle.textAlignment = FTCoreTextAlignementCenter;
- [result addObject:titleStyle];
- FTCoreTextStyle *imageStyle = [FTCoreTextStyle new];
- imageStyle.paragraphInset = UIEdgeInsetsMake(0,0,0,0);
- imageStyle.name = FTCoreTextTagImage;
- imageStyle.textAlignment = FTCoreTextAlignementCenter;
- [result addObject:imageStyle];
- [imageStyle release];
- FTCoreTextStyle *firstLetterStyle = [FTCoreTextStyle new];
- firstLetterStyle.name = @"firstLetter";
- firstLetterStyle.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:30.f];
- [result addObject:firstLetterStyle];
- [firstLetterStyle release];
- FTCoreTextStyle *linkStyle = [defaultStyle copy];
- linkStyle.name = FTCoreTextTagLink;
- linkStyle.color = [UIColor orangeColor];
- [result addObject:linkStyle];
- [linkStyle release];
- FTCoreTextStyle *subtitleStyle = [FTCoreTextStyle styleWithName:@"subtitle"];
- subtitleStyle.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:25.f];
- subtitleStyle.color = [UIColor brownColor];
- subtitleStyle.paragraphInset = UIEdgeInsetsMake(10, 0, 10, 0);
- [result addObject:subtitleStyle];
- FTCoreTextStyle *bulletStyle = [defaultStyle copy];
- bulletStyle.name = FTCoreTextTagBullet;
- bulletStyle.bulletFont = [UIFont fontWithName:@"TimesNewRomanPSMT" size:16.f];
- bulletStyle.bulletColor = [UIColor orangeColor];
- bulletStyle.bulletCharacter = @"❧";
- [result addObject:bulletStyle];
- [bulletStyle release];
- FTCoreTextStyle *italicStyle = [defaultStyle copy];
- italicStyle.name = @"italic";
- italicStyle.underlined = YES;
- italicStyle.font = [UIFont fontWithName:@"TimesNewRomanPS-ItalicMT" size:16.f];
- [result addObject:italicStyle];
- [italicStyle release];
- FTCoreTextStyle *boldStyle = [defaultStyle copy];
- boldStyle.name = @"bold";
- boldStyle.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:16.f];
- [result addObject:boldStyle];
- [boldStyle release];
- FTCoreTextStyle *coloredStyle = [defaultStyle copy];
- [coloredStyle setName:@"colored"];
- [coloredStyle setColor:[UIColor redColor]];
- [result addObject:coloredStyle];
- [defaultStyle release];
- return result;
- }
- /**
- * FTCoreTextViewDelegate
- */
- - (void)coreTextView:(FTCoreTextView *)acoreTextView receivedTouchOnData:(NSDictionary *)data {
- CGRect frame = CGRectFromString([data objectForKey:FTCoreTextDataFrame]);
- if (CGRectEqualToRect(CGRectZero, frame)) return;
- frame.origin.x -= 3;
- frame.origin.y -= 1;
- frame.size.width += 6;
- frame.size.height += 6;
- UIView *view = [[UIView alloc] initWithFrame:frame];
- [view.layer setCornerRadius:3];
- [view setBackgroundColor:[UIColor orangeColor]];
- [view setAlpha:0];
- [acoreTextView.superview addSubview:view];
- [UIView animateWithDuration:0.2 animations:^{
- [view setAlpha:0.4];
- } completion:^(BOOL finished) {
- [UIView animateWithDuration:0.5 animations:^{
- [view setAlpha:0];
- }];
- }];
- return;
- NSURL *url = [data objectForKey:FTCoreTextDataURL];
- if (!url) return;
- [[UIApplication sharedApplication] openURL:url];
- }
注:内容中的标签必须是定制,必要时需求用正则替换一下图片,如将:<img src="http://www.baidu.com/img/123.png">的图片url正则出来通过SDWebImage下载到本地
取出下载地址,在Library/Cacehes/download/kdlkaklklfkakfaasfklafalksf.png,替换后的格式如下:
- <_image>app绝对路径/Library/Cacehes/download/kdlkaklklfkakfaasfklafalksf.png</_image>
3.有一种情况复杂情况下,使用上述三种RTLabel、RCLabel、FTCoreText都不会达到很好的控制,
就是在内容中有大量网络图片,像UIView显示的大量数学公式类的图片,这种情况使用
UIWebView结合CSS控制会达到比较好的效果如图,部分代码如下:
- //预加载webView视图到_webViewAry
- _webView = [[FDWebView alloc] initWithFrame:CGRectMake(FD_SCREEN_MAIN_WIDTH*i, 61, FD_SCREEN_MAIN_WIDTH, FD_SCREEN_SHOW_HEIGHT)];
- [_webView setBackgroundColor:[UIColor whiteColor]];
- _webView.tag = 2000+i;
- [_webView setDataDetectorTypes:UIDataDetectorTypeNone];
- [_webView setOpaque:YES];
- //webView滚动条控制
- [(UIScrollView *)[[_webView subviews] objectAtIndex:0] setBounces:NO];
- _webView.scrollView.bounces = NO;
- _webView.scrollView.alwaysBounceHorizontal = NO;
- _webView.scrollView.showsHorizontalScrollIndicator = NO;
- _webView.scrollView.showsVerticalScrollIndicator = YES;
- [_webViewAry addObject:_webView];
- /**
- * 核心考点图文混排处理
- */
- - (void)setCoreTestValueForDic:(BookTopicObject *)aTopicObject autoHeight:(BOOL)autoHeight
- {
- //汇总创建HTML主体
- NSMutableString *_conString = [NSMutableString stringWithString:@"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no' /><style type='text/css'>@import url('weibo.css');</style></head><body>"];
- for (TopicSectionObject *_sectionObject in aTopicObject.sectionAry) {
- if (![_sectionObject.text isEqualToString:@""]) {
- NSString *content = [HtmlString transformString:_sectionObject.text];
- //解析
- [_conString appendFormat:@"<div class='titHead'><p class='title'>%@</p></div>", _sectionObject.title];
- //描述
- NSMutableString *_tmpStr = [NSMutableString stringWithString:content];
- [_conString appendFormat:@"<div class='txtConts'>%@</div><div class='xdbox' style='height:40px;'></div>", _tmpStr];
- }
- }
- //_conString = (NSMutableString *)[_conString stringByReplacingOccurrencesOfString:@"<br />" withString:@""];
- //结尾
- [_conString appendString:@"</body></html>"];
- [self setHTMLForString:_conString];
- //是否自适应高度
- if (autoHeight) {
- CGFloat _height = 0.0f;
- //正文
- _height += [_conString sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
- [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, _height)];
- }
- }
- /**
- * 格式化字符串
- */
- + (NSString *)transformString:(NSString *)originalStr
- {
- //originalStr = [NSString stringWithFormat:@"中国人<img src='b966133768a30e1cbddfcf5db8e2ca16' />%@<img src='http://www.kankanews.com/ICkengine/wp-content/themes/wsxcm3.0/images/logo.png' />",originalStr];
- NSString *text = originalStr;
- //获取图片url地址并保存
- static NSString *_apiUrl;
- if (_apiUrl == nil) {
- _apiUrl = [[[NSObject SDGetConfig] objectForKey:@"apiUrl"] copy];
- }
- //解析img的src
- NSString *regTags = @"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
- NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
- options:NSRegularExpressionCaseInsensitive // 还可以加一些选项,例如:不区分大小写
- error:nil];
- NSArray* match = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
- if (match.count != 0)
- {
- NSMutableString *_targetImageHtml;
- for (NSTextCheckingResult *matc in match)
- {
- NSRange range = [matc range];
- //原图片img的html
- NSString *_tmpString = [originalStr substringWithRange:range];
- NSString *_regEx = @"<img[^>]+src=['\"](.*?)['\"][^>]*>";
- NSString *_keyString = [_tmpString stringByReplacingOccurrencesOfRegex:_regEx withString:@"$1"];
- if (![_keyString hasPrefix:@"http://"]) {
- //新url
- _targetImageHtml = [NSMutableString stringWithFormat:@"<img src='%@/atth/m/%@_0_15.png' />", _apiUrl, _keyString];
- //替换url
- text = [text stringByReplacingOccurrencesOfString:_tmpString withString:[NSString stringWithFormat:@"%@ ", _targetImageHtml]];
- }else{
- _targetImageHtml = [NSMutableString stringWithFormat:@"<img src='%@' />", _keyString];
- text = [text stringByReplacingOccurrencesOfString:_tmpString withString:[NSString stringWithFormat:@"%@ ", _targetImageHtml]];
- }
- }
- }
- return text;
- }
- /**
- * 显示html赋值数据
- */
- -(void)setHTMLForString:(NSString *)string
- {
- [self loadHTMLString:string baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] resourcePath] isDirectory: YES]];
- }
效果如下,文字和图片样式还得CSS控制一下,像对齐格式,图片位置等:
最后,以下各种显示图文混排的方式,得根据我们在开发app的实际的不同需求,再选择一个最佳方案
就OK了,图文混排中还要考虑cell内容显示效率的问题,图片最好采用异步多线程预下载处理,这样体验上
会更好一些。
原文链接:http://blog.csdn.net/lgm252008/article/details/39251399
这篇关于通过RTLabel、RCLabel、FTCoreText及webView结合SDWebImage等4种方式实现左滑或下拉中cell中图文混排使用场景方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!