精简计算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

几个需要注意的地方:

最新文章

  1. mac brew install redis 报错
  2. 【PHP小项目使用MVC架构】
  3. 使用Resource Owner Password Credentials Grant授权发放Token
  4. 当PHP引擎试图实例化一个未知类的操作
  5. DOJO官方API翻译或解读-dojo/store (自定制存储器)
  6. angularjs2 学习笔记(六) Form
  7. 关于ES6扩展属性
  8. 简单工厂(Simple Pattern)模式
  9. 【C++】【斐波那契】求第几个斐波那契数字。
  10. JDBC入门连接MySQL查数据
  11. jquery data方法取值与js attr取值的区别
  12. js 作用域,变量提升
  13. Shell函数返回值、删除函数、在终端调用函数
  14. java初学者必看经典
  15. Find命令, find用法,
  16. Web前端性能优化——如何提高页面加载速度
  17. 一键脚本清理DEBIAN系统无用组件 减少系统资源
  18. js的&quot;|&quot;
  19. 腾讯QQ家族任意支付QB+修改资料csrf
  20. D3_book 7 area

热门文章

  1. nuxt踩过的坑
  2. Oracle 12c Lnux 启动脚本
  3. java面试①整体流程
  4. 每天一道剑指offer-二叉树的下一个结点1
  5. [CQOI 2018]交错序列
  6. *** Terminating app due to uncaught exception &#39;NSUnknownKeyException&#39;, reason: &#39;[&lt;WKWebViewConfiguration 0x1701bcd20&gt; setValue:forUndefinedKey:]: this class is not key value coding-compliant for the k
  7. [硬件知识]OP(Over-provisioning)预留空间
  8. DataGridView删除多行选中数据
  9. MVC 使用Quartz.Net组件实现定时计划任务
  10. 左连接sql