精简计算UITableView文本高度

本人视频教程系类   iOS中CALayer的使用

最终效果:

核心源码(计算文本高度的类)

NSString+StringHeight.h 与 NSString+StringHeight.m

//
// NSString+StringHeight.h
// USA
//
// Created by YouXianMing on 14/12/10.
// Copyright (c) 2014年 fuhuaqi. All rights reserved.
// #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> @interface NSString (StringHeight) - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width; @end
//
// NSString+StringHeight.m
// USA
//
// Created by YouXianMing on 14/12/10.
// Copyright (c) 2014年 fuhuaqi. All rights reserved.
// #import "NSString+StringHeight.h" @implementation NSString (StringHeight) - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width {
CGFloat height = ; if (self.length == ) {
height = ;
} else { // 字体
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:.f]};
if (font) {
attribute = @{NSFontAttributeName: font};
} // 尺寸
CGSize retSize = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size; height = retSize.height;
} return height;
} @end

cell的源码:

WordCell.h 与 WordCell.m

//
// WordCell.h
// WordHeight
//
// Created by YouXianMing on 14/12/16.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <UIKit/UIKit.h> @interface WordCell : UITableViewCell @property (nonatomic, strong) UILabel *words; @end
//
// WordCell.m
// WordHeight
//
// Created by YouXianMing on 14/12/16.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "WordCell.h" @implementation WordCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_words = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
_words.font = [UIFont systemFontOfSize:.f];
_words.textColor = [UIColor grayColor];
_words.numberOfLines = ; [self addSubview:_words];
} return self;
} @end

控制器源码:

//
// ViewController.m
// WordHeight
//
// Created by YouXianMing on 14/12/16.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "ViewController.h"
#import "WordCell.h"
#import "NSString+StringHeight.h" static NSString *wordCellReused = @"WordCell"; @interface ViewController ()<UITableViewDelegate, UITableViewDataSource> @property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *wordsArray;
@property (nonatomic, strong) NSMutableArray *wordsArrayHeight; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 关闭状态栏
[UIApplication sharedApplication].statusBarHidden = YES; // 创建数据源(谷歌翻译,莫见笑)
_wordsArray = [NSMutableArray array];
[_wordsArray addObject:
@"游贤明是一个iOS开发工程师,热爱技术,热爱生活,乐于奉献,喜欢打游戏,喜欢吃东西,是个吃货,喜欢学习,深信天道酬勤!"];
[_wordsArray addObject:
@"遊賢明はiOS開発エンジニア、愛する技術で、生活を愛し、献身、ゲームが好き、好きなものを食べて、美食愛好家、天道酬勤を学ぶことが好きで、信じ!"];
[_wordsArray addObject:
@"YouXianMing ist ein ios - entwickler, liebe, Leben, liebe, hingabe, Wie Spiele, der Gern Essen, ist ein Nahrungsmittel, Wie Lernen, Davon überzeugt, dass Gott!!!!!!!"];
[_wordsArray addObject:
@"YouXianMing 한 iOS 개발 엔지니어, 사랑 사랑 기술, 생활, 기꺼이 바치다, 좋아하는 게임만 좋아하는 것을 좋아하는 사람이다 가축, 학습, 확신하다 천도 보수 자주!"];
[_wordsArray addObject:
@"¡Gira el sabio es un ingeniero, el desarrollo de la tecnología de los ama, ama la vida, dedicación, como jugar el juego, me gusta comer, es un tragón, como el aprendizaje, convencidos de que Philip!"];
[_wordsArray addObject:
@"ว่ายน้ำที่ชาญฉลาดเป็น iOS วิศวกรพัฒนาเทคโนโลยีและรักชีวิตรักและทุ่มเทและชอบเล่นเกมชอบกินอะไรดีเลยชอบการเรียนรู้และเชื่อว่าไม่มีอะไรเลย"];
[_wordsArray addObject:
@"Nager sage est un ingénieur, le développement de la technologie iOS amour, de l'amour de la vie, de dévouement, de jouer le jeu, aime manger, c'est un bon à rien, comme l'apprentissage, convaincu que Tiandaochouqin!"];
[_wordsArray addObject:
@""]; // 创建存储数据源长度的数组
_wordsArrayHeight = [NSMutableArray array];
for (int i = ; i < _wordsArray.count; i++) {
NSString *tmpStr = _wordsArray[i];
CGFloat height = [tmpStr heightWithLabelFont:[UIFont systemFontOfSize:.f] withLabelWidth:];
[_wordsArrayHeight addObject:@(height)];
} // 创建tableView
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds
style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[_tableView registerClass:[WordCell class]
forCellReuseIdentifier:wordCellReused];
[self.view addSubview:_tableView];
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_wordsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
WordCell *cell = [tableView dequeueReusableCellWithIdentifier:wordCellReused];
cell.selectionStyle = UITableViewCellSelectionStyleNone; // 获取文本
cell.words.text = _wordsArray[indexPath.row]; // 重新设定尺寸
cell.words.frame = CGRectMake(, , , ); // 约束后适配
[cell.words sizeToFit]; return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [_wordsArrayHeight[indexPath.row] floatValue];
} @end

几个需要注意的地方:

精简计算UITableView文本高度的更多相关文章

  1. YYLabel计算富文本高度-膜拜大神

    http://www.jianshu.com/p/07cd655fee7e YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:C ...

  2. 用Model来计算cell的高度

    用Model来计算cell的高度 效果: 将计算cell高度的方法直接移植到Model当中,初始化的瞬间就计算好了高度,非常好用! 源码: Model // // Model.h // // Copy ...

  3. 计算纯文本情况下RichTextBox实际高度的正确方法(.NET)

    2016-07-17重大更新           其实有更好.更系统的方法,也是最近才发现的,分享给大家!! /// <summary> /// /// </summary> ...

  4. Swift - 计算文本高度

    Swift - 计算文本高度 效果 源码 // // String+StringHeight.swift // StringHeight // // Created by YouXianMing on ...

  5. iOS开发总结-UITableView 自定义cell和动态计算cell的高度

    UITableView cell自定义头文件:shopCell.h#import <UIKit/UIKit.h>@interface shopCell : UITableViewCell@ ...

  6. AutoLayout深入浅出五[UITableView动态高度]

    本文转载至 http://grayluo.github.io//WeiFocusIo/autolayout/2015/02/01/autolayout5/ 我们经常会遇到UITableViewCell ...

  7. AutoLayout处理UITableView动态高度

    我们经常会遇到UITableViewCell的高度要跟随内容而调整,在未引入AutoLayout之前,我们使用以下方法计算Label高度,然后heightForRowAtIndexPath中返回计算的 ...

  8. iOS不得姐项目--精华模块上拉下拉的注意事项,日期显示,重构子控制器,计算cell的高度(只计算一次),图片帖子的显示

    一.上拉下拉注意事项 使用MJRefresh中的上拉控件自动设置透明 当请求下页数据通过page的时候,注意的是上拉加载更多数据失败的问题,下拉加载数据失败了,页数应该还原.或者是请求成功的时候再将页 ...

  9. iOS6 以上设置文本高度,行高(转)

    2013-12-09     我来说两句   来源:冻僵的企鹅'zone   收藏    我要投稿 在iOS 7之前,常用下面这个方法计算文本高度sizeWithFont:constrainedToS ...

随机推荐

  1. ruby + phantomjs 自动化测试 - GA

    说起测试GA,真是一件枯燥乏味,重复性很高的工作,那么为什么我们不使用自动化测试代替它呢,显然,很多公司的产品迭代太快,ga也变化的比较频繁,但是确保ga工作正常,对于其他部门的工作是有很大帮助的,由 ...

  2. UOJ #356. 【JOI2017春季合宿】Port Facility

    Description 小M有两个本质不同的栈. 无聊的小M找来了n个玩具.之后小M把这n个玩具随机顺序加入某一个栈或把他们弹出. 现在小M告诉你每个玩具的入栈和出栈时间,现在她想考考小S,有多少种方 ...

  3. 二进制转化、<<、>>、>>>移位运算

    参考资料: https://www.cnblogs.com/wxb20/p/6033458.html https://www.cnblogs.com/joahyau/p/6420619.html ht ...

  4. linux中echo命令详解

    linux的echo命令, 在shell编程中极为常用, 在终端下打印变量value的时候也是常常用到的, 因此有必要了解下echo的用法 echo命令的功能是在显示器上显示一段文字,一般起到一个提示 ...

  5. Walkway.js – 创建简约的 SVG 线条动画

    Walkway.js 是一个使用线条和路径元素组成 SVG 动画图像的简单方法.只需根据提供的配置对象创建一个新的 Walkway 实例就可以了.这种效果特别适合那些崇尚简约设计风格的网页.目前, W ...

  6. subltime快捷键

    subltime 是一款快速开发各种文档的软件,本文主要介绍使用编写HTML,文章末尾提供绿色版安装包下载工具 A快捷键说明 Ctrl+Shift+P:打开命令面板Ctrl+P:搜索项目中的文件Ctr ...

  7. AVPlayer 音乐播放后台播放,以及锁屏主题设置

    第一步:在appDelegate中通知app支持后台播放:在方法 - (BOOL)application:(UIApplication *)application didFinishLaunching ...

  8. Anychart隐藏属性

    一.嵌入字体的使用 font标签可以使用嵌入字体,只需加入embed="true"即可.

  9. 在 CentOS7 上安装 zookeeper-3.5.2 服务

    [root@centos-linux src]# pwd /usr/local/src # 1.创建 /usr/local/src/zookeeper 文件夹 [root@centos-linux s ...

  10. Spring学习手札(一)

    Spring能做什么 1. 能根据配置文件创建及组装对象之间的依赖关系: 2. 面向切面编程,能帮助我们无耦合的实现日志记录,性能统计,安全控制等: 3. 提供第三方数据访问框架(如Hibernate ...