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







郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。