IOS UITableCell adaptive height

Source: Internet
Author: User

IOS UITableCell adaptive height

Example: displays a list of news.

 

First, you must have a Model class -- New

 

New. h:

 

//

// News. h

// Cellhight

//

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

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

//

 

# Import

 

@ 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];

}

 

 

// If the class does not have an attribute with the same name as the key in the dictionary, this method is executed to overwrite this method to prevent crashes.

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

{

 

 

 

 

}

@ End


Create a UITableCell class to set the cell height.

The NewsListCell. h code is:

 

//

// NewsListCell. h

// Cellhight

//

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

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

//

 

# Import

@ Class News;

 

@ Interface NewsListCell: UITableViewCell

 

@ Property (nonatomic, retain) News * news;

 

 

//

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

 

@ End


The NewsListCell. m code is:

 

 

//

// 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

{

 

// Title

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

_ TitleLabel. backgroundColor = [UIColor yellowColor];

_ TitleLabel. font = [UIFont systemFontOfSize: 20.0];

[Self. contentView addSubview: _ titleLabel];

 

// Content

_ 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;

 

// Modify the height of summmartlabel

CGRect summaryrect = _ summarylabel. frame;

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

_ Summarylabel. frame = summaryrect;

 

 

}

 

// Set the height. Calculate the height of the current row based on the input data.

+ (CGFloat) cellHigth :( News *) news

{

 

 

// Variable computing

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

 

 

// The returned result is unchangeable + keb

 

Return 10 + 40 + 10 + summaryHight + 20;

 

 

 

}

 

// Calculate the height of news content (either horizontally or vertically fixed)

+ (CGFloat) summaryheight :( NSString *) summary

{

// The size of the moment line required for text rendering. As required, the width is fixed to 280 and the height is set to 10000 (that is, the height is calculated based on the text) the width is related to the label width of the displayed text (the same size)

CGSize contextSize = CGSizeMake (280,100 00 );

 

// The font size set during calculation, which must be consistent with the font size of the label of the displayed text

NSDictionary * attributes =@{ NSFontAttributeName: [UIFont systemFontOfSize: 17.0]}; // string provided by the system class. Set the font (17 associated with the label)

 

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

 

Return summaryRect. size. height; // only one of them is required.

 

 

 

}

 

 

-(Void) awakeFromNib

{

// Initialization code

}

 

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

{

[Super setSelected: selected animated: animated];

 

// Configure the view for the selected state

}

 

@ End


The code in the controller is:

 

 

//

// 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 );

 

// Register

[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];

}

 

// Set row high restriction. After cell is set, the cell does not exist when the row is set;

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

{

// Define the method of the class for computing in the cell class. input the data object and return the calculated height.

 

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



 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.