Cannot set cell alpha in cellForRowAtIndexPath - ios

In one part of my code, i call
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
to get a number of cells, and then I change their alphas to .35. This works, and the cells look faded.
However, when I scroll the tableview, the cells that move out of the window and then move back are no longer are faded. This happens even though in cellForRowAtIndexPath the alpha for each disabled row is set to .35.
Right before returning the cells in cellForRowAtIndexPath I log
NSLog(#"%f", cell.alpha);
And it returns .35
However, the cell is not faded after scrolling? It appears as if it's alpha magically gets changed back to 1 before being displayed.
Following is my implementation of cellForRowAtIndexPath in my Section class
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if ([self disabled])
{
cell = [SectionedTableViewController tableView:tableView dequeueReusableCellWithIdentifier:#"CellDisabled" style:UITableViewCellStyleDefault];
cell.alpha = .35;
}
else
{
cell = [SectionedTableViewController tableView:tableView dequeueReusableCellWithIdentifier:#"CellEnabled" style:UITableViewCellStyleDefault];
cell.alpha = 1;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//if-else block that only sets labels is here omitted
if (cell.textLabel.text == [[cs objectAtIndex:[self c]] type])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(#"%f", cell.alpha);
return cell;
}
And the view controller that coordinates these sections gets cells from them like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Alpha: %f", [[[self sections] objectAtIndex:indexPath.section] tableView:tableView cellForRowAtIndexPath:indexPath].alpha);
return [[[self sections] objectAtIndex:indexPath.section] tableView:tableView cellForRowAtIndexPath:indexPath];
}
(and the NSLog is logging appropriate alpha values)

Adding all subviews to cell's contentView and use the following string in -cellForRowAtIndexPath:
cell.contentView.alpha = {needed_value};
will works for you.

This issue is probably due to cells being reused in the table view. There is a better way to do this:
You should create an NSMutableDictionary in your view controller and just set keys for the indexes that should be faded.
Then, in cellForRowAtIndexPath, while you are setting up the cell, set the alpha based on whether or not the index exists as a key in the dictionary.
This solution will work without any weird behavior.

Make sure you are setting alpha value for cell.contentView too. Also set alpha in tableView:willDisplayCell:forRowAtIndexPath: as it might not work in iOS 7

Related

Adding background for TableView sections iOS

I have a section with dynamic multiple rows and I need to separate all the section with the background as shown in the image below.
Specifically those border lines for all the section. Pease let me know how can I make it possible.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
return ProductArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *arr = [ProductArray objectAtIndex:section];
return arr.count;
}
Please refer to this
.
I tried adding header and footer, But I am not understanding how to add that rectangle box image for the entire section.
Put View in your cell after make outlet of that view. And use to cellForRowAtIndexPath this method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TableViewCell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.viewBackGround.backgroundColor = [UIColor redColor];
return cell;
}
For above requirement, I would like to suggest you the below approach.
create only one section with multiple rows.
Each row of UITableView will have UITableViewCell
Inside UITableViewCell create content view for which we are gonna add the border
Each row of UITableViewCell will have another UITableView(inside content view) whose methods are handled by UITableViewCell cells
Change UITableView (inside) height based on number of rows.
provide height of UITableViewCell based on the number of rows + orderID Header.

iOS get current and previous selected UITableViewCells from cellForRowAtIndexPath method

So basically what I am doing now is expanding my cells by selecting on them and using heightForRowAtIndexPath to change their height and if I select on it again or select a different cell those cells will expand or go back to their normal size.
However, upon the cell expanding I have some extra data to show in the expanded section, change the background color of the cell and set some other properties that I have defined in my tableviewcell subclass. So as an example when the cell is in its normal height the background will be light green. When its expanded it needs to be white. I set my tableviewcell subclass property (a BOOL) so that when its time to loop through the cells again (cellforRowatindexpath) i can update these properties as needed. Unfortunately, I haven't been able to find a way to get the current cell thats been selected in cellForRowAtIndexPath.
Here is the relevant code below. Keep in mind that I want to keep track of the current cell selected and the previous cell (if different from the current one) so that i can update both cells properties. Only one cell can be expanded at a time. When the current cell is selected and expanded the previous one(if applicable) will contract back to normal height. My configureCell method is just there to assign the properties based its BOOL property.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier forIndexPath:indexPath];
[cell configureCell:self.item[indexPath.row] isCollapsed:cell.isCollapsed];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *currentCell;
MyCustomCell *previousCell;
self.currentSelectedIndex = indexPath;
//assign previous and current if previous is nil
if(!self.previousSelectedIndex){
self.previousSelectedIndex = self.currentSelectedIndex;
currentCell = [tableView cellForRowAtIndexPath:self.currentSelectedIndex];
currentCell.isCollapsed = NO;
}
//we have tapped the same cell as before
else if(self.previousSelectedIndex == self.currentSelectedIndex){
previousCell = [tableView cellForRowAtIndexPath:self.previousSelectedIndex];
previousCell.isCollapsed = YES;
self.previousSelectedIndex = self.currentSelectedIndex = nil;
}
//if they aren't equal, then collapse the previous selected cell
//and expand the current selected cell
else{
previousCell = [tableView cellForRowAtIndexPath:self.previousSelectedIndex];
previousCell.isCollapsed = YES;
currentCell = [tableView cellForRowAtIndexPath:self.currentSelectedIndex];
currentCell.isCollapsed = NO;
self.previousSelectedIndex = self.currentSelectedIndex;
}
[tableView beginUpdates];
if(self.currentSelectedIndex){
[tableView reloadRowsAtIndexPaths:#[self.currentSelectedIndex, self.previousSelectedIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
}
[tableView endUpdates];
}
So, obviously my current and previous cell will be trashed once we leave this method since they are local but I am struggling with how to:
a. reload the cells which would cause cellForRowAtIndexPath to execute again(this works when trying to use reloadRows - but maybe I'm doing that wrong)
b.once cellForRowAtIndex starts going through the cells how to capture the currentCell and the previousCell so that i can update its content as I described above. [dequeueReusableCellWithIdentifier:myIdentifier] just gets a new cell which I do not want obviously.
The cells expand and contract fine so thats not an issue.

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

Drawing string on uiview over contentview of tableviewcell draws same content again and again

Because using three labels over UITableViewCell slowed down tableview scroll performance I tried drawing directly on UIView that I dragged over the prototype cell. While this significantly improved scroll performance, this got me into another problem.
Actually I am drawing the contents of a feed. After six or seven unique rows (for 20 records), rows are duplicate. They show the same content starting from top of tableview. However When I tap on those repeated cells the content changes to what it should have been.
After researching I found six or seven is the number of rows actually visible on the screen. So this should have been display update error but I am not sure should I do to fix this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"newsCell";
NewsCell *cell = (NewsCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (indexPath.row < feeds.count) {
dict = [feeds objectAtIndex:indexPath.row];
[cell setNewsHeading:[dict objectForKey:#"title"] pubDate:[dict objectForKey:#"pubDate"] newsExcerpt:[dict objectForKey:#"attributedDescription"]];
}
dict = nil;
return cell;
}
-(void)setNewsHeading:(NSString *)newsHeading pubDate:(NSString *)pubDate newsExcerpt:(NSAttributedString *)newsExcerpt
{
self.newsView.newsHeading = newsHeading;
self.newsView.pubDate = pubDate;
self.newsView.newsExcerpt = newsExcerpt;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [feeds count];
}
That sounds like it could be a caching issue - have you tried overriding the prepareForReuse method in your cell subclass to reset the cell contents back to the default values?

uitableview hiding 2 cells from scroll

made a table view, and it does not make sense at all but my table view is hiding some cells.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 25;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil){
cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
object= [self.results objectAtIndex:indexPath.row];
cell.textLabel.text=[object valueForKey:#"hLabel"];
return cell;
}
It does render 25 cells but I am only able to view up to 23. 2 cells are hidden below. Though if I scroll further I can see them but if I leave the scroll the view comes back, 23rd being the last cell. Hence user is not able to select either 24 or 25.
Even if I reduce the cell count, lets say to 23, still the tableview is hiding 2 cells and I am not able to access them as the scroll ends at 2 cells prior.
I think your tableview height is more than screen height.
Decrease the height of the tableview (make it fit to view bound) and it will display all the cell.
And also check that this autoresizing constraint is setted in in the zib/storyboard for tableview.
I faced a similar issue and i don't know how but when i unchecked Autolayout, the issue gets resolved. Try turning off Autolayout. i hope it helps you too.

Resources