iOS UITableCell自适应高度

列如--展示新闻信息列表.

首先得有一个Model类--New

New.h为:

//

//  News.h

//  Cellhight

//

//  Created by Dubai on 15-5-7.

//  Copyright (c) 2015年 Dubai. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface News : NSObject

@property (nonatomic,retain)
NSString *title;

@property (nonatomic,retain)
NSString *summary;

@end

New.m为:

//

//  News.h

//  Cellhight

//

//  Created by Dubai on 15-5-7.

//  Copyright (c) 2015年 Dubai. All rights reserved.

//

#import "News.h"

@implementation News

- (void)dealloc

{

self.summary =
nil;

self.title =
nil;

[super
dealloc];

}

//类中不存在与字典中key同名的属性时,会执行这个方法,重写该方法防治崩溃

- (void)setValue:(id)value forUndefinedKey:(NSString *)key

{

}

@end

其次创建一个UITableCell类来进行 设置cell的高度

NewsListCell.h的代码为:

//

//  NewsListCell.h

//  Cellhight

//

//  Created by DUbai on 15-5-7.

//  Copyright (c) 2015年 Dubai. All rights reserved.

//

#import <UIKit/UIKit.h>

@class News;

@interface NewsListCell :
UITableViewCell

@property (nonatomic,retain)
News *news;

//

+ (CGFloat)cellHigth:(News *)news;

@end

NewsListCell.m的代码为:

//

//  NewsListCell.m

//  Lesson11Cellhight

//

//  Created by DUbai on 15-5-7.

//  Copyright (c) 2015年 Dubai. All rights reserved.

//

#import "NewsListCell.h"

#import "News.h"

@interface
NewsListCell ()

{

UILabel *_titleLabel;

UILabel *_summarylabel;

}

@end

@implementation NewsListCell

- (void)dealloc

{   
self.news =
nil;

[_summarylabel
release];

[_titleLabel
release];

[super
dealloc];

}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString
*)reuseIdentifier

{

self = [super
initWithStyle:style
reuseIdentifier:reuseIdentifier];

if (self) {

// Initialization code

[self
setuoSubviews];

}

return
self;

}

- (void)setuoSubviews

{

//标题

_titleLabel = [[UILabel
alloc] initWithFrame:CGRectMake(20,
10,
280, 40)];

_titleLabel.backgroundColor = [UIColor
yellowColor];

_titleLabel.font = [UIFont
systemFontOfSize:20.0];

[self.contentView
addSubview:_titleLabel];

//内容

_summarylabel = [[UILabel
alloc] initWithFrame:CGRectMake(20,
60,
280, 30)];

_summarylabel.backgroundColor = [UIColor
cyanColor];

_summarylabel.font = [UIFont
systemFontOfSize:17.0];

_summarylabel.numberOfLines =
0;

[self.contentView
addSubview:_summarylabel];

}

- (void)setNews:(News *)news

{

if (_news != news) {

[_news
release];

_news = [news retain];

}

_titleLabel.text = news.title;

_summarylabel.text = news.summary;

//修改summmartlabel的高度

CGRect summaryrect =
_summarylabel.frame;

summaryrect.size.height = [[self
class] summaryheight:news.summary];

_summarylabel.frame = summaryrect;

}

//设置高度,根据传入数据,计算当前行高

+ (CGFloat)cellHigth:(News *)news

{

//计算可变

CGFloat summaryHight = [self
summaryheight:news.summary];

//返回不可变+keb

return 10 +
40 + 10 + summaryHight +
20;

}

//计算新闻内容
的高度(横向或竖向固定)

+ (CGFloat)summaryheight:(NSString *)summary

{

//文本渲染时需要的矩行大小,按需求:宽度固定位280,高度设置为10000(即高度根据文本计算得到的)
宽度与显示文本的label的宽度有关(一样大)

CGSize contextSize =
CGSizeMake(280,
10000);

//计算时设置的字体大小,必须与显示文本的label的字体大小保持一致

NSDictionary *attributes  =
@{NSFontAttributeName:[UIFont
systemFontOfSize:17.0]};//系统类提供的字符串.设置字体
(跟label有关 17)

CGRect summaryRect = [summary
boundingRectWithSize:contextSize options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes context:nil];

return summaryRect.size.height;//只需要其中一个

}

- (void)awakeFromNib

{

// Initialization code

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated

{

[super
setSelected:selected
animated:animated];

// Configure the view for the selected state

}

@end

控制器里的代码为:

//

//  NewsListTableViewController.m

//  Lesson11Cellhight

//

//  Created by Dubai on 15-5-7.

//  Copyright (c) 2015年 Dubai. All rights reserved.

//

#import "NewsListTableViewController.h"

#import "NewsListCell.h"

#import "News.h"

#define kNewsCell @"NewsListCell"

@interface
NewsListTableViewController ()

{

NSMutableArray *_newsArray;

}

@end

@implementation NewsListTableViewController

- (void)dealloc

{

[_newsArray
release];

[super
dealloc];

}

- (id)initWithStyle:(UITableViewStyle)style

{

self = [super
initWithStyle:style];

if (self) {

// Custom initialization

}

return
self;

}

- (void)viewDidLoad

{

[super
viewDidLoad];

NSString *filepath = [[NSBundle
mainBundle] pathForResource:@"NewsData"
ofType:@"plist"];

NSDictionary *sourceDic = [NSDictionary
dictionaryWithContentsOfFile:filepath];

_newsArray = [[NSMutableArray
alloc] initWithCapacity:50];

NSArray *sourceArray = sourceDic[@"news"];

// NSLog(@"source array = %@",sourceArray);

//NSMutableArray *newsArray = [[NSMutableArray alloc] initWithCapacity:50];

for (NSDictionary *newsDic
in sourceArray) {

News *news = [[News
alloc] init];

[news setValuesForKeysWithDictionary:newsDic];

[_newsArray
addObject:news];

[news
release];

}

NSLog(@"_newsArray = %@",_newsArray);

//注册

[self.tableView
registerClass:[NewsListCell
class] forCellReuseIdentifier:kNewsCell];

}

- (void)didReceiveMemoryWarning

{

[super
didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

if ([self
isViewLoaded]  && self.view.window ==nil ) {

self.view =
nil;

}

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

// Return the number of sections.

//return [_newsArray count];

return 1;

}

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

{

// Return the number of rows in the section.

return [_newsArray
count];

}

//设置行高限制性,设置cell后执行,即执行设置行高时 cell不存在对象;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath

{

//在cell类中
计算,定义类的方法.传入数据对象,返回计算后的高度

News *news = _newsArray[indexPath.row];

return [NewsListCell
cellHigth:news];

//return 110;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath

{

//News *bnews = [[News alloc] init];

NewsListCell *cell = [tableView
dequeueReusableCellWithIdentifier:kNewsCell
forIndexPath:indexPath];

News *anews = _newsArray[indexPath.row];

//    cell.new = news.title;

//    cell.new = news.summary;

//cell.news =bnews;

cell.news = anews;

return cell;

}

/*

// Override to support conditional editing of the table view.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

// Return NO if you do not want the specified item to be editable.

return YES;

}

*/

/*

// Override to support editing the table view.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

if (editingStyle == UITableViewCellEditingStyleDelete) {

// Delete the row from the data source

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

} else if (editingStyle == UITableViewCellEditingStyleInsert) {

// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

}

}

*/

/*

// Override to support rearranging the table view.

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath

{

}

*/

/*

// Override to support conditional rearranging of the table view.

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

// Return NO if you do not want the item to be re-orderable.

return YES;

}

*/

/*

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/

@end

时间: 2024-08-29 23:12:38

iOS UITableCell自适应高度的相关文章

iOS 8自适应高度单元格问题

iOS 8 中通过UITableViewAutomaticDimension 常量支持自适应高度的单元格(iOS 7 就要麻烦得多).但是在实际应用中,我们需要注意以下几个问题: 1. 设置好模板单元格的自动布局 模板单元格中,subviews的自动局部必须要能够把单元格撑满.也就是说,iOS 必须能够通过内容的自动布局约束计算出 cell 的高.以下面的单元格为例: cell中有上下两个 Label,上面的Label只有一行文本(lines为1),所以高度在运行时不会改变,但下面的Label是

iOS Label 自适应高度

推荐第二个 测试一,只改变numberOfLines属性,label的高度不会自适应(会有text中的一部分内容称为......) NSString *str = @"jgreijgirjeirgjierjgiu4t9eumctuv5 vtmnvghvmc5v5tgh58tc857y"; UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 100, 100)]; label.font = [UIFont s

iOS UI10_cell自适应高度

#import "MainViewController.h" #import "Cell.h" @interface MainViewController ()<UITableViewDataSource, UITableViewDelegate> @property(nonatomic, retain)NSArray *picArr; @property(nonatomic, retain)NSMutableArray *ziArr; @end @im

iOS tableViewCell自适应高度 第三发类库

转自:http://www.cnblogs.com/qianLL/p/5393331.html 在github中有许多大牛封装好的第三发类库,其中有个自适应cell高度的类库 下载地址:https://github.com/gsdios/SDAutoLayout model类 commentsModel #import "JSONModel.h" #import "getCommentData.h" @interface commentsModel : JSONMo

iOS UITableViewableViewCell自适应高度

前两天做了一个项目,中间有遇到一个问题,就是聊天的时候cell高度的问题.这是一个很多前辈都遇到过,并且很完美的解决过的问题.这里主要是记录自己的学习心得.项目中首先想到的是用三方库,可是有问题,遂放弃,自己写一个,但是没有封装.项目地址 UITableView 的属性特征什么的,这里就暂时不做介绍了. 由于聊天内容比较简单,不需要对聊天做出很多操作,只是简单的使用 UILable 进行展示即可.首先我们定义一个模型 JXChatModel // // JXChatModel.h // JXAu

iOS UITextView自适应高度UITextContainerView抖动问题

在打造一个类似于微信朋友圈评论输入框的时候,需要动态调整输入框的高度, 但是,在调整了UITextView的高度之后,继续输入会导致内容(UITextContainerView里的文字)抖动. scrollRangeToVisible 方法解决了我的问题(Swift 3): textView.scrollRangeToVisible(NSRange.init(location: 0, length: 0)) 获取UITextView内的文字高度以及行数的方法(Swift 3): let heig

【原】ios tableViewCell 自适应高度

原文:http://www.cnblogs.com/A--G/p/4819051.html 前言:之前在做一个类似微博的小需求时候,用table view实现了微博文字和图片等等的基本展示,由于文字和图片的数量问题,cell高度会受到影响. 以前的做法是在heightForRowAtIndexPath 里取出这条微博的model,计算图片和文字的高度,现在有一个简单一点的办法: 在heightForRowAtIndexPath里重新获取这个cell的高度即可, TableViewCell *ce

iOS UITableViewCell自适应高度

在cell.m文件中 1)初始化方法中: self.lalName=[[UILabel alloc] initWithFrame:CGRectMake(71, 5, 250, 40)]; [self addSubview:self.lalName]; 2)创建方法: //给用户介绍赋值并且实现自动换行 -(void)setIntroductionText:(NSString*)text{ //获得当前cell的高度 CGRect frame=[self frame]; //文本赋值 self.l

IOS UILabel 根据内容自适应高度

iOS Label 自适应高度  适配iOS7以后的版本 更多 self.contentLabelView = [[UILabel alloc] init]; self.contentLabelView.font = SYS_FONT(15); self.contentLabelView.lineBreakMode =NSLineBreakByTruncatingTail ; self.contentLabelView.textColor =  [UIColor colorWithHexStri