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
Related
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
I have a custom UITableViewCell. I want to access the cells properties i.e. a UILabel etc. I tried inserting the following code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CategorieCell *customCell = (CategorieCell *)[tableView cellForRowAtIndexPath:indexPath];
return ...
}
When I run the app, it crashed without giving me error details. The problem is with the new customCell I'm creating. Is there another way I can access the customCell.m objects?
About the crash, please note that you are using cellForRowAtIndexPath: wich is a method from the UITableViewDatasource that you have to implement, this method calls heightForRowAtIndexPath by default, so it will become a recursive
I assume that you want your custom cell in this method in order to get the height from it.
The best way to achieve this is write a class method on CategorieCell that gives you the height for a cell with certain data.
Other option is extract a method with the code to get the uitableviewcell for example
(CategorieCell*) categorieCellForIndex:(NSIndex)index selected:(BOOL)selected{
...
}
In heightForRowAtIndexPath should never be called cellForRowAtIndexPath.
The first one is called before the second one, and if you need to access to a label (for example to calculate the height of the text) you can normally init a cell.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static CategorieCell *cell;
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
cell.frame = CGRectMake(0, 0, tableView.frame.size.width-tableView.contentInset.left-tableView.contentInset.right, cell.frame.size.height);
[cell layoutIfNeeded];
}
cell.label.text = myDatasourceText;
CGFloat cellHeight = ....
return cellHeight;
}
NOTE 1:
I used dequeueReusableCellWithIdentifier supposing you are using Interface Builder, otherwise you need to use alloc] initWithStyle:...];
NOTE 2:
As you see I'm setting the frame of the cell. This is needed because otherwise your cell will be (320 x 44) as default. You instead could be in iPhone 6/6+ (i.e. screen width: 414) or in an iPad, and you could need to calculate an height of a label according with his width and his text, and for this reason you need to set the frame of the cell.
NOTE 3:
I'm assuming you have a set of equal cell structure, and for this reason I'm using a static cell, so it will be reused without allocate other useless cells.
Try to register your custom cell class like so:
[self.tableView registerClass:[CategorieCell class] forCellReuseIdentifier:NSStringFromClass([CategorieCell class]);
and then in -tableView:heightForRowAtIndexPath: do something like:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CategorieCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CategorieCell class)];
}
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.
I have a NSTimer that calls this method every fourth second:
- (void)timerDecrement
{
timerCount = timerCount-1;
[OtherViewControllerAccess updateTimeLeftLabel];
}
In the updateTimeLeftLabel in the other class:
- (void)updateTimeLeftLabel
{
int timeLeft = OtherClassAccess.timerCount;
UILabel *timeLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 10, 120, 20)];
timeLeftLabel.text = [NSString stringWithFormat:#"Tid kvar: %ih", timeLeft];
[cell addSubview:timeLeftLabel];
}
Basically I want my app to update a label in a cell in the tableview with the current time left, but the above method doesn't do anything to the call. So my question is, how can I add this subview to the cell outside the cellForRowAtIndexPath:delegate method, and then make it update that label every time the method is called.
So my question is, how can I add this subview to the cell outside the
cellForRowAtIndexPath:delegate method, and then make it update that
label every time the method is called.
The answer is, don't add subviews to a table view cell outside of cellForRowAtIndexPath. The cells belong to the table view, and you absolutely, categorically, should NOT try to modify them. That's the table view's job.
Just as a small example of what's wrong with your code, you would be adding an ever-increasing number of label views to your table view cell, one every 1/4 second. That's bad.
Second point: Which cell is "cell"? A table view manages a whole table of cells. If the user scrolls, some cells are scrolled off-screen and replaced with different cells.
Instead, you should figure out which indexPath contains the cell with your data in it, change the data in your model, and tell your table view to update the cell at the appropriate indexPath. That will cause it to redraw with updated contents.
Here is how I did something similar. I created a custom UITableViewCell class that has a timestamp UILabel:
#property (nonatomic) UILabel *labelTimestamp;
In that cell's layoutSubviews, I update the label size based on its title.
- (void)layoutSubviews {
[super layoutSubviews];
[self.labelTimestamp sizeToFit];
...
}
I then have an NSTimer firing every minute in my UIViewController that update that label in every visible cell (you could adapt to update only one cell with a specific indexPath).
- (void)timerDidFire
{
NSArray *visibleCells = [self.tableView visibleCells];
for (GroupViewCell *cell in visibleCells) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[cell.labelTimestamp setText:[self.groupController statusUpdateDateAtIndexPath:indexPath]];
[cell setNeedsLayout];
}
}
I would keep the set up of the cell's centralized in cellForRowAtIndexPath: method. You can keep using your NSTimer to call reloadRowsAtIndexPaths:withRowAnimation: with the indexes of the cell/cells you want to update and therefore cellForRowAtIndexPath: will be called again.
Why don't you put that value (which you want to display in the cell) in a variable and assign a UILabel that value. In your updateTimeLeftLabel just call [self.tableView reloadData].
You can reload whole table or some specific rows but that needs connection of datasource with your views . You have to change your dataset first and then you have to call
[self.tableview reloadData];
another method is that, after changing dataset call
[self.tableview reloadRowsAtIndexPaths:indexPath withAnimation:animation];
2nd method requires indexPath i.e. you know that which cell you need to edit .
My problem was same . In my project there were 2 TextFields and 1 label in each cell . Now depending on the values of 2 textfields, I have to show their multiplication in UILabel. and this is my code.
-(void)textFieldDidChange:(id)sender{
UITextField *_sender = (UITextField *)sender;
int tag = _sender.tag;
int row = tag / 3;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
((UILabel *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:row * 3 + 2]).text = #"hello";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"here");
static NSString *CellIdentifier = #"procedureDetailsCell";
UITableViewCell *cell = (procedureCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[((procedureCell *)cell).Quantity setTag:indexPath.row + 0];
[((procedureCell *)cell).Quantity addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[((procedureCell *)cell).Cost setTag:indexPath.row + 1];
[((procedureCell *)cell).Cost addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[((procedureCell *)cell).total setTag:indexPath.row + 2];
return cell;
}
Logic is simple I have used Custom TableViewCell which contains 2 textfields and 1 label. when one of the two textfield's value is changed we are calling "textFieldDidChange" method which finds indexpath and then find UITableViewcell and then updates its lastview's text value, that is our UILabel. we have to give unique tag to each of our views .
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.