微信朋友圈评论列表功能简单实现

转载微信朋友圈评论列表功能简单实现

概述

最近朋友问了一个微信朋友圈评论列表的实现,加之以前也做过类似的功能,这两天抽时间重新完善和设计了一下,以此文作为总结和大家分享,欢迎大家批评指教
源码见文末

截图

微信Fed

需求描述

  • 列表页展现消息流
  • 消息内容支持全文收起功能
  • 消息支持评论,评论条数不限制
  • 用户信息支持点击进入用户中心

技术分析

  • 列表页展现消息流
  • 消息流一般采用tableview实现
  • tableview实现又分为自动布局绝对布局(即Frame布局)。
  • 自动布局可以采用UITableView-FDTemplateLayoutCell分方案实施。这种方案可以自动计算cell高度,但笔者认为一下几种情况,不要使用自动布局。对于简单页面的屏幕适配,当然首推自动布局(masonry)
    • cell交互要求较高
    • cell布局复杂,view元素较多, 层级深
    • 对性能要求较高
  • Frame布局
    • 缺点:计算复杂(相对于masonry自动布局)
    • 优点: 性能好,可控性强,易动画,扩展维护成本低

两种布局方式不是本文的重点,这里不在多说,笔者偏好是Frame布局,本文案例也将采用这种方式

  • 消息内容支持全文收起功能
    • 需要计算文字行数,判断两种方式
  • 消息支持评论,评论条数不限制
    • 对于一般社区类帖子评论,都会有个评论列表页,在原帖下方最多显示3条评论,然后查看更多,直接跳转到评论列表页;这种情况不用考虑性能和内存问题,直接用三个Label实现即可。
    • 对于消息评论不限条数,那么就要好好设计了,笔者这里采用的是cell里面放tableView的方式来承载无限评论条数
  • 用户信息支持点击进入用户中心

程序架构

目录结构

|____Controller
| |____SQTopicTableViewController.h
| |____SQTopicTableViewController.m
| |____SQUserCenterViewController.h
| |____SQUserCenterViewController.m
|____Model
| |____SQCommentModel.h
| |____SQCommentModel.m
| |____SQTopicModel.h
| |____SQTopicModel.m
|____View
| |____SQCommentTableViewCell.h
| |____SQCommentTableViewCell.m
| |____SQTopicTableViewCell.h
| |____SQTopicTableViewCell.m
|____ViewModel
| |____SQCommentCellViewModel.h
| |____SQCommentCellViewModel.m
| |____SQTopicCellViewModel.h
| |____SQTopicCellViewModel.m
|____Library
| |____TTTAttributedLabel
| | |____TTTAttributedLabel.h
| | |____TTTAttributedLabel.m

项目采用的是MVVM的分层结构


MVVM
  • 项目的ViewModel的作用
  • 实际项目中我们从服务器获取的数据,转换为模型(Model)后,对应的数据有些不能直接显示在视图(View)上,需要二次处理。
  • 那么处理放在哪里里好?
  • 笔者在一些项目里,直接把这些数据格式化直接放在了Model里,有的是在set/get方法直接格式化数据,有的是增加辅助属性,这就是传说中的胖模型吧.
  • 后果是模型复用性降低;因为相同的模型,相同字段,在不同场景要被格式化的样式不一样。增加的辅助字段,越来越多,有时自己都回忆不起来这个辅助字段的实际意义。想一想还是保持模型的「纯真」吧,将复杂的数据处理,交给各自View对应的ViewModel;
  • tableView结合viewModel的使用

tableviewcell高度计算,是tableView使用以及优化的重点对象,最好的方式莫过于高度缓存。但如何计算,如何缓存,如何使用的?笔者分享一下此项目采用的方案:

  • ViewModel模型,持有Model,并开放cell中各个子view布局属性,以及部分格式化后的模型字段,以及cellHeight缓存cell高度
@interface SQTopicCellViewModel : NSObject
// 持有原始数据模型
@property(nonatomic, strong) SQTopicModel *topicModel;
@property(nonatomic, strong) NSArray *commentCellViewModels;
// cell 各个子元素布局属性
@property(nonatomic, assign) CGRect iconF;
@property(nonatomic, assign) CGRect nameLabelF;
@property(nonatomic, assign) CGRect contentF;
@property(nonatomic, assign) CGRect toggoleButtonF;
@property(nonatomic, assign) CGRect tableviewF;
// 缓存cell高度
@property(nonatomic, assign) CGFloat cellHeight;
@end
  • 重新ViewModel的set模型方法(即项目的setTopicModel方法),根据数据计算cell各个资源的布局,以及格式化数据
- (void)setTopicModel:(SQTopicModel *)topicModel
{
    _topicModel = topicModel;

    CGFloat margin = 15;
    CGFloat conentW = [UIScreen mainScreen].bounds.size.width - 2 * margin;

    CGFloat iconX = margin;
    CGFloat iconY = margin;
    CGFloat iconWH = 50;


    CGFloat nameLabelX = CGRectGetMaxX(self.iconF) + margin;
    CGFloat nameLabelW = 250;
    CGFloat nameLabelH = 20;

    CGFloat contentLabelX = nameLabelX;
    CGFloat contentLabelW = conentW - margin - iconWH;
    CGFloat contentLabelH = 0;

    UIFont *contentLabelFont = [UIFont systemFontOfSize:15];
    contentLabelH = [topicModel.content boundingRectWithSize:CGSizeMake(contentLabelW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:contentLabelFont} context:nil].size.height;

    int lineNum = contentLabelH / contentLabelFont.lineHeight;


    CGFloat toggoleButtonX = contentLabelX;
    CGFloat toggoleButtonW = 32;
    CGFloat toggoleButtonH = 0;

    if (lineNum > 5) {

        if (topicModel.isExpanded == NO) {
            contentLabelH = contentLabelFont.lineHeight * 5;
        }
        toggoleButtonH = 20;

    }

    // 计算cell高度,坐标Y值
    。。。

}
  • cell持有自身ViewModel模型, 在tableView的数据源给cell注入viewModel时,确定cell各元素布局以及数据
- (void)setTopicViewModel:(SQTopicCellViewModel *)topicViewModel
{
    _topicViewModel = topicViewModel;

    self.icon.image = [UIImage imageNamed:topicViewModel.topicModel.icon];
    self.icon.frame = topicViewModel.iconF;

    self.nameLabel.frame = topicViewModel.nameLabelF;
    self.nameLabel.text = topicViewModel.topicModel.userame;

    。。。
}
  • viewModel高度(cellHeight)计算,某些cell的子元素,根据数据不一定显示,需要单独判端。笔者开始采用的是在计算完成一个元素后,就判断是否显示,并确定y值。但是如果后面元素的显示如果依赖于上一元素的位置,甚至是嵌套依赖,那么情况就会变得过于复杂,笔者把这部分放到了最后,只根据高度是否大于0来判读,各元素是否显示,在计算是通过赋值自身高度是否为零即可
- (void)setTopicModel:(SQTopicModel *)topicModel
{
    _topicModel = topicModel;
    // 计算各个子元素的大小
    。。。

    // 计算cell高度,各元素坐标Y值
    if (nameLabelH > 0) {
        self.cellHeight += margin;
        self.nameLabelF = CGRectMake(nameLabelX, self.cellHeight, nameLabelW, nameLabelH);
        self.cellHeight += nameLabelH;
    }

    if (contentLabelH > 0) {
        self.cellHeight += margin * 0.5;
        self.contentF = CGRectMake(contentLabelX, self.cellHeight, contentLabelW, contentLabelH);
        self.cellHeight += contentLabelH;

    }

    if (toggoleButtonH > 0) {
        self.cellHeight += margin * 0.5;
        self.toggoleButtonF = CGRectMake(toggoleButtonX,  self.cellHeight, toggoleButtonW, toggoleButtonH);
        self.cellHeight += toggoleButtonH;
    }
    。。。。
    self.cellHeight += margin * 0.5;

}
  • cell评论区实现

cell持有一个tableview(专门给评论列表显示), 把代理、数据源给自己。每一条评论也设计成tableviewcell, 有着自己的viewModel(SQCommentCellViewModel),实现逻辑上述相似,不在重复

@interface SQTopicTableViewCell()<UITableViewDelegate, UITableViewDataSource, SQCommentTableViewCellDelegate>
@property(nonatomic, strong) UIImageView *icon;
@property(nonatomic, strong) TTTAttributedLabel *nameLabel;
@property(nonatomic, strong) TTTAttributedLabel *topicLabel;
@property(nonatomic, strong) UITableView *commentTableView;
@property(nonatomic, strong) UIButton *toggoleButton;
@end

@implementation SQTopicTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        // 其他元素
        。。。

        // tableview
        _commentTableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _commentTableView.delegate = self;
        _commentTableView.dataSource = self;
        _commentTableView.backgroundColor = [UIColor colorWithRed:236/256.0 green:236/256.0 blue:236/256.0 alpha:1];
        _commentTableView.bounces = NO;
        _commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_commentTableView registerClass:[SQCommentTableViewCell class] forCellReuseIdentifier:@"comment"];
        [self.contentView addSubview:_commentTableView];

    }

    return self;
}

- (void)setTopicViewModel:(SQTopicCellViewModel *)topicViewModel
{
    _topicViewModel = topicViewModel;

    // 其他布局数据设值
    。。。。

    //tablevew布局,加载数据
    self.commentTableView.frame = topicViewModel.tableviewF; // 这里的tableviewF的计算在上层ViewModel中(即____SQTopicTableViewCell)
    [self.commentTableView reloadData];  // 数据源初始化以及组装也在SQTopicCellViewModel中commentCellViewModels

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    SQCommentCellViewModel *topicViewModel = self.topicViewModel.commentCellViewModels[indexPath.row];

    return topicViewModel.cellHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.topicViewModel.commentCellViewModels.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SQCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comment"];
    cell.commentCellVM = self.topicViewModel.commentCellViewModels[indexPath.row];
    cell.delegate = self;
    return cell;
}

@end

评论的tableview高度是如何计算的?
SQTopicCellViewModel中持有commentCellViewModels数组, 在将评论原始数据转化我ViewModel中时,能确定各个评论cell的高度,数组中所有高度加起来,就是评论tableview的高度

- (void)setTopicModel:(SQTopicModel *)topicModel
{
    _topicModel = topicModel;

    。。。

    CGFloat tableViewX = contentLabelX;
    CGFloat tableViewW = [UIScreen mainScreen].bounds.size.width - margin - tableViewX;
    CGFloat tableViewH = 0;

    NSArray *commentModels = topicModel.commentModels;

    NSMutableArray *mutableVMs = [NSMutableArray array];

    if (commentModels.count > 0) {
       for (int i = 0; i < commentModels.count; i++) {
           SQCommentCellViewModel *commmentVM = [[SQCommentCellViewModel alloc] init];
           commmentVM.maxW = tableViewW;        // 先要给出宽度,方便评论cell根据文字计算出自身高度
           commmentVM.commentModel = commentModels[i];

           tableViewH += commmentVM.cellHeight; // 所有高度加起来

           [mutableVMs addObject:commmentVM];   
       }
    }
    self.commentCellViewModels = mutableVMs.copy;// 构造数据源

    。。。

}
  • 展开全文实现
  • 正文高度大于5行,显示全文按钮;点击全文按钮,展开全文,按钮变为收起;点击收起,折叠内容
  • 文字计算判断行数,笔者这里直接更具字体的lineHeight计算的,如果是AttribedString,带行距时,可能计算不准,这里没找到更好的方式,如有更好的方式,欢迎再评论区回复。
  • 在模型中增加了一个辅助属性isExpanded用来标识当前数据是否被展开。目的是防止:1.cell重用,导致布局混乱。2. 展开的数据在滑动后,被关闭
。。。

CGFloat contentLabelX = nameLabelX;
CGFloat contentLabelW = conentW - margin - iconWH;
CGFloat contentLabelH = 0;

UIFont *contentLabelFont = [UIFont systemFontOfSize:15];
contentLabelH = [topicModel.content boundingRectWithSize:CGSizeMake(contentLabelW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:contentLabelFont} context:nil].size.height;

int lineNum = contentLabelH / contentLabelFont.lineHeight;

CGFloat toggoleButtonX = contentLabelX;
CGFloat toggoleButtonW = 32;
CGFloat toggoleButtonH = 0;

if (lineNum > 5) {
    if (topicModel.isExpanded == NO) {
        contentLabelH = contentLabelFont.lineHeight * 5;
    }
    toggoleButtonH = 20;
}

。。。

收起/全文事件代理给vc

- (void)cellToggleExpentContent:(SQTopicTableViewCell *)cell
{
    // 查询位置
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    SQTopicCellViewModel *viewModel = self.dataArray[indexPath.row];
    // 修改展开状态
    viewModel.topicModel.expanded = !viewModel.topicModel.isExpanded;

    // 更新布局
    SQTopicCellViewModel *newViewModel = [[SQTopicCellViewModel alloc] init];
    newViewModel.topicModel = viewModel.topicModel;

    // 替换数据
    [self.dataArray replaceObjectAtIndex:indexPath.row withObject:newViewModel];

    // 局部刷新表格
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

}
  • TTTAttributedLabel链接点击实现

// TTTAttributedLabel初始化
_contentLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
_contentLabel.numberOfLines = 0;
_contentLabel.textColor = [UIColor blackColor];
_contentLabel.font = [UIFont systemFontOfSize:14];
_contentLabel.linkAttributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:0/256.0 green:87/256.0 blue:168/256.0 alpha:1]};
_contentLabel.activeLinkAttributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:140/256.0 green:87/256.0 blue:168/256.0 alpha:1]};

// TTTAttributedLabel 添加事件
TTTAttributedLabelLink *fromLink = [self.contentLabel addLinkToPhoneNumber:commentCellVM.commentModel.from withRange:NSMakeRange(0, commentCellVM.commentModel.from.length)];

fromLink.linkTapBlock = ^(TTTAttributedLabel *label, TTTAttributedLabelLink *link)
{

    if (self.delegate && [self.delegate respondsToSelector:@selector(cell:didUserInfoClicked:)]) {
        [self.delegate cell:self didUserInfoClicked:commentCellVM.commentModel.from];
    }

};

  • cell事件传递实现

事件传递三种方式delegate, notification, block。笔者项目采用的是代理delegate,将所有事件代理给viewcontroller

代理的事件

  • 主帖用户信息点击
  • 展开全文点击
  • 评论用户信息点击
  • 评论cell点击

其中评论用户信息点击,评论cell点击采用的是代理嵌套代理的方式实现。应为这两个事件是在子tableview(评论taleview)的cell上,中间有个嵌套关系,暂时没有找到方法,可以减少这一层嵌套。个人认为,两层代理嵌套,是可接受的,并不会太混乱;,如有更好的方式,请在评论区回复。

@protocol SQTopicTableViewCellDelegate <NSObject>
@optional
- (void)cell:(SQTopicTableViewCell *)cell didUserClicked:(NSString *)username;
- (void)cell:(SQTopicTableViewCell *)cell didReplyClicked:(SQCommentModel *)commentModel;
- (void)cellToggleExpentContent:(SQTopicTableViewCell *)cell;
@end

源码

github-commentDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容