精简计算UITableView文本高度

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

    if (self.length == 0) {
        height = 0;
    } else {

        // 字体
        NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:18.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(0, 0, 320, 0)];
        _words.font          = [UIFont systemFontOfSize:18.f];
        _words.textColor     = [UIColor grayColor];
        _words.numberOfLines = 0;

        [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 = 0; i < _wordsArray.count; i++) {
        NSString *tmpStr = _wordsArray[i];
        CGFloat height   = [tmpStr heightWithLabelFont:[UIFont systemFontOfSize:18.f] withLabelWidth:320];
        [_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(0, 0, 320, 0);

    // 约束后适配
    [cell.words sizeToFit];

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_wordsArrayHeight[indexPath.row] floatValue];
}

@end

几个需要注意的地方:

时间: 2024-08-07 22:00:07

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

用Model来计算cell的高度

用Model来计算cell的高度 效果: 将计算cell高度的方法直接移植到Model当中,初始化的瞬间就计算好了高度,非常好用! 源码: Model // // Model.h // // Copyright (c) 2014年 Y.X. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface Model : NSObject @property (n

iOS中的长文本高度计算

很多的时候如果只是要显示一些简单的短文本,比如确定.取消什么的,一个UILabel就足够了.   但是某些情况下,文本较长.包含这些文本的View的高度取决于文本的高度.比如我们常见的 微博.虽然文本所占的高度内容限制在了140字,但是用户发的微博是140字内的多少字, 我们不清楚.那么在用到UITableView的时候,每条微博所在的Cell的高度都要根据其中包含的 文字及其他内容所需要的实际高度来进行设定.当然,此文只讨论文本的高度计算问题,而且 难度也只集中在文本的动态高度上.    长文

计算一行文本的高度

计算一行文本的高度   说明 有时候我们需要知道指定的几行文本的高度,此工具用于解决此种问题.   源码 // // NSString+LabelWidthAndHeight.h // ZiPeiYi // // Created by YouXianMing on 15/12/9. // Copyright 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit

《Python自然语言处理》——1.1 语言计算:文本和词汇

1.1 语言计算:文本和词汇 我们都对文本非常熟悉,因为我们每天都在进行阅读和写作.在本书中,把文本视为编写程序的原始数据,并通过很多有趣的编程方式来处理和分析文本.但在能写这些程序之前,必须得从了解Python解释器开始. Python入门 Python与用户友好交互的方式之一包括你可以在交互式解释器直接输入代码--解释器将运行你的Python代码的程序.你可以通过一个叫做交互式开发环境(Interactive Development Environment,IDLE)的简单图形接口来访问Py

《Python自然语言处理》——第1章 语言处理与Python 1.1 语言计算:文本和词汇

第1章 语言处理与Python 我们能够很容易地得到数百万数量级的文本.假设我们会写一些简单的程序,那可以用它来做些什么?本章将解决以下几个问题. (1)通过将技术性较简单的程序与大规模文本结合起来,我们能实现什么? (2)如何自动地提取出关键字和词组,用来总结文本的风格和内容? (3)Python编程语言为上述工作提供了哪些工具和技术? (4)自然语言处理中有哪些有趣的挑战呢? 本章分为风格完全不同的两部分.在1.1节,我们将进行一些与语言相关的编程练习而不去解释它们是如何实现的.在1.2节,

ScrollView与ListView合用(正确计算Listview的高度)的问题解决_Android

首先,ListView不能直接用,要自定义一个,然后重写onMeasure()方法: 复制代码 代码如下: @Override  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {      int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,              MeasureSpec.AT_MOST);    

Cell嵌套UITableView自动布局

前言 最近有很多小伙伴们都问我有没有cell里面再嵌套tableview的demo,老说不知道怎么做,不知道怎么计算高度啊.其实这个很简单的,昨天晚上正好有点时间,写了这个demo. 本篇文章只讲如何在cell中嵌套UITableView,只是粗浅知识点,只教大家基本的如何去计算UITableview的高度.这里模拟评论写了个demo,增加或者删除一条评论都可以马上更新,得到正确的显示. 效果图 这里使用了100条数据,但是界面并不卡.这里使用了笔者所开源的自动计算cell的高度来计算行高的,而

iOS使用UITableView实现的富文本编辑器

本文讲的是iOS使用UITableView实现的富文本编辑器,公司最近做一个项目,其中有一个模块是富文本编辑模块,之前没做个类似的功能模块,本来以为这个功能很常见应该会有已经造好的轮子,或许我只要找到轮子,研究下轮子,然后修改打磨轮子,这件事就八九不离十了.不过,还是 too young to simple 了,有些事,还是得自己去面对的,或许这就叫做成长,感觉最近一年,对于编程这件事,更多了一点热爱,我感觉我不配过只会复制粘贴代码的人生,编程需要有挑战.所以,遇到困难,保持一份正念,路其实就在

个数-用C语言计算文本单词总数及每个单词出现频率

问题描述 用C语言计算文本单词总数及每个单词出现频率 C语言计算创建文本中单词的个数(单词以空格或者逗号等其他非字母符号分隔)且每个单词出现的次数 解决方案 直接单词放一个hashtable,然后单词做key,个数做value 解决方案二: 用VB写一个给你 Imports System.Text.RegularExpressions Module Module1 Sub Main() Dim s As String = "Four score and seven years ago our f