UICollectionViewCell change background color - iphone

I have UICollectionview with sections and two cell class.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
myCell *cell;
firstDayInMonth = [self dayWeekStart:[self getDateFromItem:dateFromStart section:indexPath.section row:1]];
if (indexPath.row < firstDayInMonth) {
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellCalendarEmpty" forIndexPath:indexPath];
} else {
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellCalendar" forIndexPath:indexPath];
}
}
I have start item, section and period. Beginning from the start section and item i need to change background color cell depending on period. i need to change only cellCalendar. I use cellCalendarEmpty to move first cellCalendar.

Fix by handling both branches of the case (all cases) when you configure, e.g.:
if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){
cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
cell.titleLabel.textColor = [UIColor whiteColor];
} else {
cell.backgroundColor = [UIColor whiteColor]; // whatever the default color is
}
If you're using a custom subclass of UICollectionViewCell, you may also reset to defaults by implementing the prepareForReuse method.

Related

UICollectionviewcell change background

How to change the background in the cell if I know the section number and the item number? The code below shows how I tried to do it.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
cell.titleLabel.text = [NSString stringWithFormat:#"%i",indexPath.item-dayStart+2];
if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){
cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
cell.titleLabel.textColor = [UIColor whiteColor];
}
return cell;
But if I do so during scrolling painted not just the relevant cell.
What you're seeing is the cell getting reused as the view scrolls, the reused cell still has the background color from an earlier use. Fix by handling both branches of the case (all cases) when you configure, e.g.:
if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){
cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
cell.titleLabel.textColor = [UIColor whiteColor];
} else {
cell.backgroundColor = [UIColor whiteColor]; // whatever the default color is
}
If you're using a custom subclass of UICollectionViewCell, you may also reset to defaults by implementing the prepareForReuse method.
you are using CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
the collection view is dequeueing ReusableCells so when scrolling it than again uses the old cells changing your desired requirement.it happens with background color and images
add this line before condition
CalendarCollectionViewCell *cell=[NSBundle mainBundle] loadNibNamed:#"CalendarCollectionViewCell" owner:self options:nil] objectAtIndex:0];
do not use
if(!cell){....

Cells attached to each other in a UICollectionView

Why, when I create a CollectionView, and dequeque two cells with different identifier, the latter are attached to each other?
The cells with the same identifier have equal distance between them, instead the cells with different identifier are stuck together.
Here my code:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 2;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
if (section == 0) {
return 1;
}
if (section == 1) {
return 10;
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
UICollectionViewCell *cell;
if (indexPath.section == 0) {
cell = [cv dequeueReusableCellWithReuseIdentifier:#"AddCell" forIndexPath:indexPath];
UIImageView *cellImage = (UIImageView *)[cell viewWithTag:1];
[cellImage setImage:[UIImage imageNamed:#"pulsante_trasparente.png"]];
}
else if (indexPath.section == 1){
cell = [cv dequeueReusableCellWithReuseIdentifier:#"PictureCell" forIndexPath:indexPath];
UIImageView *cellImage = (UIImageView*)[cell viewWithTag:1];
[cellImage setImage:[UIImage imageNamed:#"mi.png"]];
}
return cell;
}
Please help me!
Implement this method to get space between cells of different sections:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
{
return UIEdgeInsetsMake(Top_Gap, Left_Gap, Buttom_Gap, Right_Gap);
}
Have you tried to set the minimum Spacing for cells at a negative value if not do so by going to the UICollectionView in your xib and selecting the inspector and customizing the minimum space there. I have a image for you showing what I mean:

UITableView's background color becoming white when section is empty

Here is the deal: I have a UITableView with 2 sections, and I want to display a "no data" cell when the first section is empty, so that the 2 section headers are not stuck together (cause it looks weird).
It works great (even though I had trouble making it work at first, see this thread). I'm using viewForFooterInSection :
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
if(section == 0)
{
if([firstSectionArray count] == 0)
return 40;
else
return 0;
}
return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
if(section == 0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(200, 10, 50, 44)];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithWhite:0.6 alpha:1.0];
label.textAlignment = UITextAlignmentCenter;
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
label.text = #"No row";
return [label autorelease];
}
return nil;
}
But the background color turns plain white when I display the section footer view. See image:
alt text http://img683.yfrog.com/img683/9480/uitableviewproblem.png
I like it better when the background is filled with empty cells. Does anyone have any idea how to do that? Thanks
The background is filled with empty cells when you have no footer. So do not implement a viewForFooterInSection (or titleForFooterInSection) method, and you will get the "empty cells" effect.
I'd recommend that you return a cell indicating that there are no entries to show, like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (matches.count>0) {
// Do your usual thing here
} else {
static NSString *cellId = #"noDataCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.textColor = [UIColor grayColor];
}
cell.textLabel.text = #"Aucun match";
return cell;
}
}
And of course, you would have to tell UIKit that you always have at least one cell in your section... I've added the isDeletingRow case that seems to trouble you (in comment).
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0) return matches.count>0 ? matches.count : (isDeletingRow ? 0 : 1);
// Set 'isDeletingRow' to YES when a delete is being committed to the table, in that case we let UIKit know that we indeed took care of the delete...
// And cover the other sections too...
}
When you are committing the edits, you need to set isDeletingRow for numberOfRowsInSection to return a satisfactory value...
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
isDeletingRow = YES;
// Your current code when a row is deleted here...
isDeletingRow = NO;
if (matches.count==0) [self.tableView performSelector:#selector(reloadData) withObject:nil afterDelay:0.5];
}
}

iPhone + UITableView + format cells

I am using following method in my application:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
}
}
When I run the application I have 7 rows in my table. According to above function only the cell of first row (row number 0) should be formatted (because of the if condition).
Cell of 1st row (row number 0) is formatted properly (as per desired output). But if I scroll the table down one more cell is displayed as formatted: cell at row number 5.
Why so?
I agree with Vladimir's answer.
However, i also believe you should follow a different approach.
In the current situation you are formatting your cell frequently, as the method gets called in each scroll, and this leads you to a suboptimal performance.
A more elegant solution is to format 1st row differently than others only "once" : when you create your cells.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier;
if(indexPath.row == 0)
CellIdentifier = #"1stRow";
else
CellIdentifier = #"OtherRows";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.row == 0){
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
// Other cell properties:textColor,font,...
}
else{
cell.contentView.backgroundColor = [UIColor blackColor];
cell.contentView.alpha = 1;
//Other cell properties: textColor,font...
}
}
cell.textLabel.text = .....
return cell;
}
I think the reason is that TableView reuses already existing cells and displays them if it is possible. What happens here - when table is scrolled and row 0 becomes invisible then itscorresponding cell is used for a newly displayed row. So if you're reusing cells you must reset their properties:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5; }
else
{
// reset cell background to default value
}
}

How do I set UITableViewCellSelectionStyle property to some custom color?

I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.
How can we use a color other than those defined in the reference?
The best way to set the selection is to set the selectedBackgroundView on the cell when you construct it.
i.e.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SelectedCellBackground.png"]] autorelease];
}
// configure the cell
}
The image used should have a nice gradient (like the default selection). If you just want a flat color, you can use a UIView instead of a UIImageView and set the backgroundColor to the color you want.
This background is then automatically applied when the row is selected.
Setting the selectedBackgroundView seems to have no effect when the cell.selectionStyle is set to UITableViewCellSelectionStyleNone. When I don't set the style is just uses the default gray.
Using the first suggestion that inserts the custom UIView into the cell does manipulate the cell but it doesn't show up when the cell is touched, only after the selected action is completed which is too late because I'm pushing to a new view. How do I get the selected view in the cell to display before the beginning of the selected operation?
If you have subclassed a UITableViewCell, then you can customise the various elements of the cell by overriding the following:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
EDIT for iOS7:
as Sasho stated, you also need
cell.selectionStyle = UITableViewCellSelectionStyleNone
I tried some of the above, and I actually prefer to create my own subclass of UITableViewCell and then override the touchesBegan/touchesCancelled/touchesEnded methods. To do this, ignore all the selectedBackgroundView and highlightedColor properties on the cell, and instead just set these colors manually whenever one of the above methods are called. For example, if you want to set the cell to have a green background with red text, try this (within your custom cell subclass):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//Set backgorund
self.backgroundColor = [UIColor themeBlue];
//Set text
self.textLabel.textColor = [UIColor themeWhite];
//Call super
[super touchesBegan:touches withEvent:event];
}
Note that for this to work, you need to set:
self.selectionStyle = UITableViewCellSelectionStyleNone;
Otherwise, you'll first get the current selection style.
EDIT:
I suggest using the touchesCancelled method to revert back to the original cell colors, but just ignore the touchesEnded method.
Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:
UIView* selectedView; //inside your header
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
selectedView = [[UIView alloc] initWithFrame:[cell frame]];
selectedView.backgroundColor = [UIColor greenColor]; //whatever
[cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
[selectedView release]; //clean up
}
You can choose to animate this view out when it gets deselected and will satisfy your requirements.
Sublcass UITableViewCell and override setHighlighted:animated:
You can define a custom selection color color by setting the backgroundColor (see WIllster's answer):
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
You can define a custom background image by setting the backgroundView property:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if( highlighted == YES )
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_default.png"]];
else
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_active.png"]];
[super setHighlighted:highlighted animated:animated];
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
// Set Highlighted Color
if (highlighted) {
self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
} else {
self.backgroundColor = [UIColor clearColor];
}
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Add your Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //highlight colour
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Reset Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //normal color
}
- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
cell.contentView.backgroundColor = color;
cell.backgroundColor = color;
}
To add a custom color use the below code. And to make it transparent use alpha: 0.0
cell.selectedBackgroundView = UIView(frame: CGRect.zero)
cell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)
If you use custom color and want to give it rounded corner look use:
cell.layer.cornerRadius = 8
Also, use this for better animation and feel
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}