iOS: How to fit UILabel text in UITableViewCell? - ios

This is my first iOS project, so I am learning a lot and have to learn more.
I learnt that in order to fit more items on UITableViewCell, I need to subclass it and then use it. I created TransactionCell and in my ViewController I use it as
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// make last cell visible: http://stackoverflow.com/questions/11928085/uitableview-not-visible-the-last-cell-when-scroll-down
tableView.contentInset = UIEdgeInsetsMake(0, 0, 120, 0);
[tableView registerNib:[UINib nibWithNibName:#"TransactionCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
TransactionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[TransactionCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
TransactionModel *transactionModel = self.transactionsModel.transactions[(NSUInteger) indexPath.row];
cell.dateAndMonth.text = transactionModel.date;
cell.name.text = transactionModel.name;
cell.amount.text = transactionModel.amount;
cell.categoryImage.image = [self getShortImage:[UIImage imageNamed:transactionModel.category]];
cell.transactionTypeImage.image = [self getShortImage:[UIImage imageNamed:#"Debit"]];
cell.imageView.contentMode = UIViewContentModeCenter;
return cell;
}
Also, I set the height of cell as
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100;
}
My xib looks like
When I run the project however, I see the following
Things don't fit up!
Question
- How do I make the labels appear completely on TransactionCell?
- How do I fit all the elements in a single row without cutting off
I am sure I need to learn something else, but not sure what

While your label is selected in the xib, go to the autoshrink section in the attributes inspector and change the option to minimum font scale, I usually set it to around 0.5.

Add three separate UILabel inside the cell and set the frame for three different size.

As #Shadowfiend told,you have to work with the auto layout and auto resizing.
Check this link: http://www.appcoda.com/self-sizing-cells/
It is nice tutorial on auto resizing the cells and well described too.
Hope it help.

Related

How to get dynamically height for UITableViewCell

I created Customized tableViewCell, I added UIView SubView in UITableViewCell. So my all dynamic Text & Image Content in UIView and it will change according to text and image size.
but now getting error in HeightforRowAtIndex , here i returned direct UIView frame.size.height+10; it working fine in iOS8.1 but it will not work below all version.
Here below added piece of code & with image.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
_cellbackground=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 310, 0)];
_cellbackground.backgroundColor=[UIColor whiteColor];
[cell addSubview:_cellbackground];
return cell;
}
Here _cellbackground view, height will change dynamically according to text and image content.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return _cellbackground.frame.size.height+10;
}
here I return height according to UIView height, but it will working only on (iPhone 6s)iOS8.1. but others it will not work properly.
Please suggest me best way to get height enter image description here this image from iPhone 5(7.1) , it will not work properly.
enter image description here it is from iPhone 6(8.1) working properly.
Please guide me best solution to return height.( HeightForRowAtIndex).
for dynamically height for UITableViewCell set in viewDidLoad
_tableView.estimatedRowHeight = 100.0;
_tableView.rowHeight = UITableViewAutomaticDimension;
this set automatic cell height as per content height
Let me know if this works...

How to get cell in heightForRowAtIndexPath?

I have created custom cells in my app.I want to get the each cell in HeightForRowAtIndexPath.Please tell me how can i get the custom cell in this method.I have tried this code but this causes infinite loop & finally crash the app.
HomeCell *cell=(HomeCell *)[tableView cellForRowAtIndexPath:indexPath];
EDIT:
I Have tried this but it gives me cell height as zero.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"HomeCell";
HomeCell *cell = (HomeCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
float tv_view_height=cell.tv_post.frame.size.height;
float like_count_height=cell.label_like_count.frame.size.height;
float first_comment_height=cell.first_comment.frame.size.height;
float second_comment_height=cell.second_cmment.frame.size.height;
float third_comment_height=cell.third_comment.frame.size.height;
Post *user_post=[arr_post objectAtIndex:indexPath.row];
float comment_count=[user_post.comment_count intValue];
if(comment_count<=0)
{
first_comment_height=0;
second_comment_height=0;
third_comment_height=0;
}
else if(comment_count==1)
{
second_comment_height=0;
third_comment_height=0;
}
else if(comment_count==2)
{
third_comment_height=0;
}
float like_count=[user_post.like_count intValue];
if(like_count<=0)
{
like_count_height=0;
}
float total_height=tv_view_height+like_count_height+first_comment_height+second_comment_height+third_comment_height;
NSLog(#"total heigh is %f'",total_height);
return total_height;
}
Please tell which is the best way?
How to get cell in heightForRowAtIndexPath?
It's impossible, because when -heightForRowAtIndexPath is called, no cells are created yet. You need to understand how the UITableView works:
UITableView asks it's datasource how many sections it will have
-numberOfSectionsInTableView
At this point there are no cells created.
UITableView asks it's datasource how many rows each section will have
-numberOfRowsInSection
At this point there are no cells created.
UITableView asks it's delegate height of each visible row, to know where cells will be located
-heightForRowAtIndexPath
At this point there are no cells created.
UITableView asks it's datasource to give it a cell to display at given index path
-cellForRowAtIndexPath
At this point the cell is created.
The height of each cell you can calculate from data model. You don't need the cell – you already know the frame width that will contain a comment, you know it's content, you know it's font, you know linebreak mode, etc. So, you can calculate height. For example:
CGFloat commentsHeight = 0;
Post *user_post = [arr_post objectAtIndex:indexPath.row];
for (NSString *comment in user_post.comments)
{
CGRect commentrect = [comment boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 18, FLT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin)
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:15]}
context:nil];
commentsHeight += commentrect.size.height;
}
And you can calculate height of the other components of cell from its data model.
But now, in 2015, it's not the best way. You really would be better to read the tutorials, which showed #Zil, and do it with Autolayout.
You should declare an array for storing TableView cells in cellForRowAtIndexPath and you can use stored cells in heightForRowAtIndexPath. Lets Try using this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"HomeCellID";
HomeCell *cell = (HomeCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[[HomeCell alloc] init] autorelease];
}
// Store table view cells in an array
if (![tableViewCells containsObject:cell]) {
[tableViewCells addObject:cell];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([tableViewCellsArray objectAtIndex:indexPath.row]) {
HomeCell *cell = (HomeCell *)[tableViewCells objectAtIndex:indexPath.row];
// Process your Code
}
return yourCalculatedCellHeight;
}
I would recommend you to take the height form a configuration collection on your viewController.
Something like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height;
CellConfiguration * selectedCellConfiguration =[_cellConfigurations objectAtIndex:indexPath.row];
switch (selectedCellConfiguration.type) {
case TheTypeYouNeed:
return TheValueYouNeed
default:
height = 44.0f;
break;
}
return height;
}
You could create a new cell from scratch, simply by HomeCell *sexyCell = [[HomeCell alloc]init];
or dequeue one like you did in cellForRow (tableView.dequeueWithReuseIdentifier:).
Though I advise creating one from scratch and disposing it after (setting it to nil), because if you dequeue it there they'll go in queue and cause heavy memory leaks and end up with many cells for the same indexPath.
What you COULD do is the following :
Create a cell with alloc init
Fill it with the real data
use .layoutsubviews on its view
calculate it's size and apply it to your real cell
What you SHOULD do :
Use auto layout and add all the constraints that are necessary, all your labels will size dynamically. It takes about 3 or 4 hours to get the basics of Auto layout, and about a month of regular use to really get the hang of it with ease.
I strongly strongly strongly suggest you do NOT resize using the frame of objects, most labels and views will resize like they should without having to write any code if you use constraints properly.
Once you have done that, because you have cells of varying heights, is using the DynamicHeight property of the tableview and the slight adjustements that comes with it. You can find
A great tutorial here
The same updated tutorial for swift (more up to date but you'd need to translate)
This amazing StackOverflow answer which you MUST read
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:indexpath.row inSection:0];
Custom Cell *cell = [tableview cellForRowAtIndexPath:indexPath];
By this , you will get each cell in your method

How to make a cell overlap?

I want to make cells overlapping.
What I did is
Adjust the tableview's contentSize:
int count = [self.tableView numberOfRowsInSection:0];
self.tableView.contentSize = CGSizeMake(self.view.frame.size.width ,(100 * count - 30 * (count - 1)));
And set the cellForRowAtIndexPath :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
cell.contentView.backgroundColor = [UIColor orangeColor];
}
if (indexPath.row != 0) {
UITableViewCell *currentCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]];
[currentCell setFrame:CGRectMake(0, - 30, self.view.frame.size.width, 100)];
}
return cell;
}
But when I test, this is not working.
Any help? Thanks.
What is happing with your code is that the values that you are manually setting inside tableView:cellForRowAtIndexPath: are getting overwritten by the UITableViewController layout methods.
You are not supposed to edit the frame of a table view cell directly since this is an attribute that is set by UITableViewController internally. You should only interact with this by using methods of the UITableViewDelegate protocol. (tableView:heightForRowAtIndexPath:, ...)
IMHO the best way (cleanest one) to implement what you are describing is to subclass UICollectionView instead of UITableView and define a custom layout.
However if you wanna go the hacky way you can achieve an apparent row overlapping in many different ways.
Just as an example, you could create two different row types, one with height 30 and one with height 70, where the first one represents the overlapping part of the row and the second one represents the not-overlapping part of the row. Then use the first type for even rows and the second one for odd rows.
Hope this helps.
p.s. i'm really sorry if my english is not the best

UITableViewCell detailTextLabel disappears when scrolling

I'm using an array of strings where I set the detailTextLabel from. Initially all subtitles are set correctly but if I scroll the detailTextLabel disappears.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"personCell" forIndexPath:indexPath];
Person *person = [_persons objectAtIndex:indexPath.row];
cell.textLabel.text = person.name;
cell.detailTextLabel.text = person.phone;
// also tried setNeedsLayout but does not help
[cell setNeedsLayout];
return cell;
}
I'm using an iPhone 6 and iOS 8. I'm also using storyboard and set the UITableViewCell style to Subtitle.
OK, now that we've found the problem (with the nil phone number text on the person) you could solve it a couple of ways.
It seems that you don't want to set the text to blank. I imagine this is due to the fact that it lays out the cell in an odd way with the title pushed up to the top but nothing underneath it. Understandable.
So, you could create a custom UITableViewCell subclass. In it you can manage the layout yourself and if the number is nil lay it out one way and if it has a phone number lay it out a different way.
An easier way would be to use two different prototype cells instead.
In the storyboard create two prototype cells.
One with type Basic and give it a reuseIdentifier noPhoneNumberCell.
The other with type Subtitle and a reuse identifier phoneNumberCell.
Then in the code you can do something like this...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Person *person = [_persons objectAtIndex:indexPath.row];
UITableViewCell *cell;
if (person.phone) {
cell = [tableView dequeueReusableCellWithIdentifier:#"phoneNumberCell" forIndexPath:indexPath];
cell.detailTextLabel.text = person.phone;
} else {
cell = [tableView dequeueReusableCellWithIdentifier:#"noPhoneNumberCell" forIndexPath:indexPath];
}
cell.textLabel.text = person.name;
return cell;
}
This will now create two queues of cells. One for people with phone numbers and one for people without.
This way you don't mix the two and so avoid the problem you are facing.
[cell.detailTextLabel sizeToFit];

UITableView with Various Custom Cells of differing heights within UIView

I am building a IOS app homepage which basically consists of the following structure -
Which is basically a UIView which contains a nested UIScrollView which inturn contains a TableView with 3 Custom Cells.
I pull data out of a dynamic array and filter it into the relevant cell - all works fine other than two issues I cant work out -
1- The custom cells are different heights in the storyboard but when the app is compiled they are always the same height - is it possible to set an auto height on the UITableView Row? If not can anyone explain how I can apply the correct height to each cell?
2- The TableView / View which wraps the table view need to expand to make all dynamic cells visible - how can I achieve this?
below is my tableview method for reference -
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier =#"CellFeed";
static NSString *CellIdentifierArtNo =#"CellArtRecNo";
static NSString *CellIdentifierBook =#"CellBooking";
UITableViewCell *cell;
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.section];
NSString * ArtPString = #"articleP";
NSString * ArtNoPString = #"article";
NSString * ArtBook = #"booking";
if([f.FeedGroup isEqualToString:ArtPString]){
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
CellHp_RecArticleWithImage *cellImage = (CellHp_RecArticleWithImage *)cell;
cellImage.selectionStyle = UITableViewCellSelectionStyleNone;
cellImage.artTitle.text = f.FeedTitle;
cellImage.artImg.text = f.FeedDesc;
cellImage.artDate.text = f.FeedDate;
cellImage.textLabel.backgroundColor=[UIColor clearColor];
return cellImage;
}
if([f.FeedGroup isEqualToString:ArtBook]){
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierBook
forIndexPath:indexPath];
CellHp_BookingAlert *cellBook = (CellHp_BookingAlert *)cell;
cellBook.selectionStyle = UITableViewCellSelectionStyleNone;
cellBook.HeadlineLbl.text = f.FeedTitle;
cellBook.TextBoxLbl.text = f.FeedDesc;
//cellBook.DateLbl.text = f.FeedDate;
return cellBook;
}
else{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierArtNo
forIndexPath:indexPath];
CellHp_RecArticleNoImage *cellNoImage = (CellHp_RecArticleNoImage *)cell;
cellNoImage.selectionStyle = UITableViewCellSelectionStyleNone;
cellNoImage.artTitle.text = f.FeedTitle;
cellNoImage.artImg.text = f.FeedDesc;
cellNoImage.artDate.text = f.FeedDate;
cellNoImage.textLabel.backgroundColor=[UIColor clearColor];
return cellNoImage;
}
Cheers
It looks like you've got custom UITableViewCell subclasses like CellHp_RecArticleNoImage or CellHp_BookingAlert (may I suggest renaming them to something a little less headache-inducing? ;) ).
In that case, if you only have 3 different cell types, you could do this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [tableView cellForAtIndexPath:indexPath];
if ([cell isKindOfClass:[CellHp_BookingAlert class])
{
return 123.0;
}
else if ([cell isKindOfClass:[CellHp_RecArticleNoImage class])
{
return ...
}
...
}
Or, you could make all your custom classes implement a height method for a cleaner solution and in heightForRowAtIndexPath: you could just get the cell and call its height method.
Re. Question 2, use UIView's sizeToFit method as Tim mentioned.
You need to implement below method to identify the height of cell.
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath
*)indexPath;
You can derive static or dynamic (data driven) cell heights from the storyboard by dequeuing them in heightForRowAtIndexPath according to the procedure outlined here: Retrieve custom prototype cell height from storyboard?
I'm not exactly sure I understand this question, but you can get the contentSize of the table view if you're trying to size the table to fit the content.

Resources