Change Cell Background Every 5 Cells - ios

Hello I want to change the color of my UITableView Cells ever 5 cells, so I would have green for cell one blue for cell two and so on. Then once I hit 5 cells, I want the colors to start over.
This is what I have so far:
if(indexPath.row % 5 == 0){
cell.backgroundColor = [UIColor blackColor];
} else if (indexPath.row % 4 == 0) {
cell.backgroundColor = [UIColor redColor];
} else if (indexPath.row % 3 == 0) {
cell.backgroundColor = [UIColor greenColor];
} else if (indexPath.row % 2 == 0) {
cell.backgroundColor = [UIColor blueColor];
} else if(indexPath.row % 1 == 0) {
cell.backgroundColor = [UIColor orangeColor];
If someone could point me in the right direction I would really appreciate it. Thank you!

You need to modulo against the same number, not different numbers. This should point you in the right direction:
static NSArray* rowColors;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
rowColors = #[[UIColor redColor], [UIColor blueColor], [UIColor greenColor], [UIColor orangeColor], [UIColor yellowColor]];
});
int rowMod = indexPath.row % rowColors.count;
UIColor* color = rowColors[rowMod];
cell.contentView.backgroundColor = color;
This approach does a few things better than your current approach:
It performs % against the same number, which is the core logic problem in what you posted
It dynamically uses rowColors.count, in case you want to add extra colors (e.g., change every 7 rows instead of every 5)
It uses an array so you don't have if/else-if/else-if/else-if getting out of control
It sets backgroundColor on cell.contentView instead of cell, which is the proper way to set a background color
The array is static and only written to once, to ensure good performance and not result in a ton of memory allocation each time you setup a cell
Hope it helps!

I think this is what you're looking for:
if(indexPath.row % 5 == 0)
{
cell.backgroundColor = [UIColor blackColor];
}
else if (indexPath.row % 5 == 1)
{
cell.backgroundColor = [UIColor redColor];
}
else if (indexPath.row % 5 == 2)
{
cell.backgroundColor = [UIColor greenColor];
}
else if (indexPath.row % 5 == 3)
{
cell.backgroundColor = [UIColor blueColor];
}
else if(indexPath.row % 5 == 4)
{
cell.backgroundColor = [UIColor orangeColor];
}
You want to keep the modulus divisor the same -- its the remainder that is actually going to be changing

Related

Where to set UITableViewCell other than in cellForRowAtIndexPath ? Objective-C

In a wish to improve UITableView performance, I'm thinking of relocating all of my UITableViewCell's settings outside cellForRowAtIndexPath.
At this moment, I have several custom cells inside my tableview that I set inside cellForRowAtIndexPath. But because of this, everytime I scroll inside my tableview and so everytime a cell has to be shown on screen, the settings is done again, causing a lag.
I've tried to put settings inside viewDidLoad by using a class variable for my cell but with no effect. Do you have any idea where I could move all of my cells' settings but especially if it's possible ?
Thanks in advance and have a nice day !
EDIT :
As asked, here is my cellForRowAtIndexPathMethod :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.delegate = self;
if ([appliedTheme hasPrefix:#"DarkMode"]) {
self.tableView.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0];
cell.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0];
cell.cardView.backgroundColor = [UIColor colorWithRed:0.30 green:0.30 blue:0.30 alpha:1.0];
cell.webServerIntroLabel.textColor = [UIColor whiteColor];
cell.webServerOptionsTitle.textColor = [UIColor whiteColor];
cell.webServerOptionsReachableAtLabel.textColor = [UIColor whiteColor];
}else {
self.tableView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
cell.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
cell.cardView.backgroundColor = [UIColor whiteColor];
cell.webServerIntroLabel.textColor = [UIColor blackColor];
cell.webServerOptionsTitle.textColor = [UIColor blackColor];
cell.webServerOptionsReachableAtLabel.textColor = [UIColor blackColor];
}
if ([CellIdentifier isEqualToString:#"webServerIntro"]) {
cell.webServerIntroImageView.image = [UIImage imageNamed:webServerIntroIconToShow];
cell.webServerIntroLabel.adjustsFontSizeToFitWidth = YES;
cell.webServerIntroLabel.numberOfLines = 0;
[cell.webServerIntroLabel sizeToFit];
cell.webServerIntroLabel.text = #"Some text";
}else if ([CellIdentifier isEqualToString:#"webServerOptions"]) {
cell.webServerOptionsTitle.adjustsFontSizeToFitWidth = YES;
cell.webServerOptionsTitle.text = NSLocalizedString(#"Web Server Options", nil);
cell.webServerOptionsStatusLabel.adjustsFontSizeToFitWidth = YES;
if (!webServerStarted) {
cell.webServerOptionsImageView.image = [UIImage imageNamed:#"Not-Checked"];
cell.webServerOptionsStatusLabel.text = NSLocalizedString(#"Not Running", nil);
cell.serverURLLabel.text = NSLocalizedString(#"Not Reachable", nil);
cell.ipAddressURLLabel.text = NSLocalizedString(#"Not Reachable", nil);
[cell.startStopWebServerButton setTitle:NSLocalizedString(#"Start Web Server", nil) forState:UIControlStateNormal];
cell.webServerStartedBool = NO;
}else {
NSString *serverURL = [self deviceName];
serverURL = [serverURL stringByReplacingOccurrencesOfString:#" " withString:#"-"];
cell.webServerOptionsImageView.image = [UIImage imageNamed:#"Checked"];
cell.webServerOptionsStatusLabel.text = NSLocalizedString(#"Running", nil);
cell.serverURLLabel.text = [NSString stringWithFormat:#"http://%#.local", serverURL];
cell.ipAddressURLLabel.text = [NSString stringWithFormat:#"%#", webUploader.serverURL];
[cell.startStopWebServerButton setTitle:NSLocalizedString(#"Stop Web Server", nil) forState:UIControlStateNormal];
cell.webServerStartedBool = YES;
}
cell.webServerOptionsStatusLabel.textColor = [UIColor lightGrayColor];
cell.webServerOptionsReachableAtLabel.adjustsFontSizeToFitWidth = YES;
cell.webServerOptionsReachableAtLabel.text = NSLocalizedString(#"Reachable At :", nil);
cell.ipAddressURLLabel.adjustsFontSizeToFitWidth = YES;
cell.ipAddressURLLabel.textColor = [UIColor lightGrayColor];
cell.ipAddressURLLabel.layer.borderWidth = 1.0f;
cell.ipAddressURLLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
cell.ipAddressURLLabel.layer.cornerRadius = 5;
cell.serverURLLabel.adjustsFontSizeToFitWidth = YES;
cell.serverURLLabel.textColor = [UIColor lightGrayColor];
cell.serverURLLabel.layer.borderWidth = 1.0f;
cell.serverURLLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
cell.serverURLLabel.layer.cornerRadius = 5;
cell.startStopWebServerButton.layer.borderWidth = 1.0f;
cell.startStopWebServerButton.layer.borderColor = [[UIColor clearColor] CGColor];
cell.startStopWebServerButton.layer.cornerRadius = 5;
cell.startStopWebServerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
if ([appliedTheme isEqualToString:#"Default-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0 green:0.478 blue:0.875 alpha:1]; /*#007ADF : Bleu iOS*/
}else if ([appliedTheme isEqualToString:#"Red-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.90 green:0.07 blue:0.00 alpha:1.0]; /*#E61100 : Rouge*/
}else if ([appliedTheme isEqualToString:#"Orange-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.83 green:0.33 blue:0.00 alpha:1.0]; /*#D35400 : Orange*/
}else if ([appliedTheme isEqualToString:#"Yellow-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.95 green:0.61 blue:0.07 alpha:1.0]; /*#F39C12 : Jaune*/
}else if ([appliedTheme isEqualToString:#"Green-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.15 green:0.68 blue:0.38 alpha:1.0]; /*#27AE60 : Vert*/
}else if ([appliedTheme isEqualToString:#"Purple-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.56 green:0.27 blue:0.68 alpha:1.0]; /*#8E44AD : Violet*/
}else if ([appliedTheme isEqualToString:#"Gray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.74 green:0.76 blue:0.78 alpha:1.0]; /*#BDC3C7 : Gris*/
}else if ([appliedTheme isEqualToString:#"DarkGray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.50 green:0.55 blue:0.55 alpha:1.0]; /*#7F8C8D : Gris foncé*/
}else if ([appliedTheme isEqualToString:#"DesaturatedBlue-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.17 green:0.24 blue:0.31 alpha:1.0]; /*#2C3E50 : Bleu désaturé*/
}else if ([appliedTheme isEqualToString:#"VeryDarkGray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0]; /*#333333 : Gris très foncé*/
}else if ([appliedTheme isEqualToString:#"Black-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:1.0]; /*#000000 : Noir*/
}else if ([appliedTheme isEqualToString:#"DarkModeDefault-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0 green:0.478 blue:0.875 alpha:1]; /*#007ADF : Bleu iOS*/
}else if ([appliedTheme isEqualToString:#"DarkModeRed-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.90 green:0.07 blue:0.00 alpha:1.0]; /*#E61100 : Rouge*/
}else if ([appliedTheme isEqualToString:#"DarkModeOrange-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.83 green:0.33 blue:0.00 alpha:1.0]; /*#D35400 : Orange*/
}else if ([appliedTheme isEqualToString:#"DarkModeYellow-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.95 green:0.61 blue:0.07 alpha:1.0]; /*#F39C12 : Jaune*/
}else if ([appliedTheme isEqualToString:#"DarkModeGreen-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.15 green:0.68 blue:0.38 alpha:1.0]; /*#27AE60 : Vert*/
}else if ([appliedTheme isEqualToString:#"DarkModePurple-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.56 green:0.27 blue:0.68 alpha:1.0]; /*#8E44AD : Violet*/
}else if ([appliedTheme isEqualToString:#"DarkModeGray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.74 green:0.76 blue:0.78 alpha:1.0]; /*#BDC3C7 : Gris*/
}else if ([appliedTheme isEqualToString:#"DarkModeDarkGray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.50 green:0.55 blue:0.55 alpha:1.0]; /*#7F8C8D : Gris foncé*/
}else if ([appliedTheme isEqualToString:#"DarkModeDesaturatedBlue-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.17 green:0.24 blue:0.31 alpha:1.0]; /*#2C3E50 : Bleu désaturé*/
}else if ([appliedTheme isEqualToString:#"DarkModeVeryDarkGray-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0]; /*#333333 : Gris très foncé*/
}else if ([appliedTheme isEqualToString:#"DarkModeBlack-Theme"]) {
cell.startStopWebServerButton.backgroundColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:1.0]; /*#000000 : Noir*/
}
}else {
}
return cell;
}
While you have a lot of code there, nothing seems like it would be dreadfully slow.
It is a minor point in term of performance, but the code that sets the tableview's background colour should be in viewWillAppear rather than cellForRowAt as there is no need to set the background colour each time a cell is dequeued.
You can also simplify this function considerably by moving all of the theme-related code into the cell subclass. Call a function on the cell passing the theme and have the cell set all of that stuff; The same amount of code will be executed, but cellForRowAt will be smaller and easier to read.
Where I think you can get some performance is by eliminating the repeated string operations related to the theme. Create a class or struct that represents your theme and use an enumeration (This stuff is much easier is Swift, but you can still do it in ObjectiveC).
If you do this, then, for example,
if ([appliedTheme hasPrefix:#"DarkMode"])
becomes
if (appliedTheme.darkMode)
A complex string comparison is replaced with a simple boolean check; this is much faster
Similarly, using an enumeration for the theme you get something like
switch (appliedTheme.theme) {
case DarkModeGreen-Theme:
...
Now an expesnsive string comparison has been replaced with a quick integer comparison.
Finally, creating UIColors is relatively expensive. You can move that into your Theme object too. When you create an instance of a Theme, expose the colours as properties. This way you get rid of the switch statement I suggested and creating the colours each time and simply say something like
cell.startStopWebServerButton.backgroundColor = appliedTheme.buttonBackgroundColor
Have to tried prepareforreuse. Apart from loading images I don't see other code that could cause the delay. Few things that might help
Even though imagenamed should return a cache image if it's already loaded, try loading images async with GCD
Is the web service code causing any delay?
Run instruments (time profiler?) to see what is causing the lag or delay

UIProgressView update itself in custom UITableViewCell

I've a UITableView populated with several custom UITableViewCell. In one of them I have a UIProgressView that will represent a percentage of data.
However when I set a progress (let's say 50%), the progress bar appear at 50% and update itself until it reach 100%...
Here the code I use to update the data :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if ([appliedTheme hasPrefix:#"DarkMode"]) {
self.tableView.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0];
cell.backgroundColor = [UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.0];
cell.cardView.backgroundColor = [UIColor colorWithRed:0.30 green:0.30 blue:0.30 alpha:1.0];
cell.storageIntroLabel.textColor = [UIColor whiteColor];
cell.storageInfoTitle.textColor = [UIColor whiteColor];
cell.deviceStorageTitle.textColor = [UIColor whiteColor];
}else {
self.tableView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
cell.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
cell.cardView.backgroundColor = [UIColor whiteColor];
cell.storageIntroLabel.textColor = [UIColor blackColor];
cell.storageInfoTitle.textColor = [UIColor blackColor];
cell.deviceStorageTitle.textColor = [UIColor blackColor];
}
if ([CellIdentifier isEqualToString:#"storageIntro"]) {
cell.storageIntroImageView.image = [UIImage imageNamed:storageIntroIconToShow];
cell.storageIntroLabel.adjustsFontSizeToFitWidth = YES;
cell.storageIntroLabel.numberOfLines = 0;
[cell.storageIntroLabel sizeToFit];
cell.storageIntroLabel.text = NSLocalizedString(#"Here you can find informations about your storage and how FileStore is using your memory by types of files", nil);
}else if ([CellIdentifier isEqualToString:#"storageInfo"]){
cell.storageInfoTitle.text = NSLocalizedString(#"Storage Informations", nil);
cell.deviceStorageTitle.adjustsFontSizeToFitWidth = YES;
cell.deviceStorageTitle.text = NSLocalizedString(#"Device Storage", nil);
cell.totalDeviceSpaceLabel.adjustsFontSizeToFitWidth = YES;
cell.totalDeviceSpaceLabel.text = NSLocalizedString(#"Total space :", nil);
cell.finalTotalDeviceSpaceLabel.text = totalDeviceSpaceString;
cell.freeDeviceSpaceLabel.adjustsFontSizeToFitWidth = YES;
cell.freeDeviceSpaceLabel.text = NSLocalizedString(#"Free space :", nil);
cell.finalFreeDeviceSpaceLabel.text = totalDeviceFreeSpaceString;
dispatch_async(dispatch_get_main_queue(), ^{
[cell.deviceStorageProgressView setProgress:50 animated:YES];
});
}else {
}
return cell;
}
Even if I doesn't use the bool animated:YES, the progress bar update itself over the time from the percentage I've set...
It doesn't mean anything to me ! Do I have to put the UIProgressView settings in another cell's delegate method ?
Thanks in advance for your help !
According to UIProgressView documentation
The current progress is represented by a floating-point value between 0.0 and 1.0, inclusive, where 1.0 indicates the completion of the task. The default value is 0.0. Values less than 0.0 and greater than 1.0 are pinned to those limits.
You are setting it to 50 which will basically be converted to upper value 1. You need to give value as 0.5 if you want 50% progress.

How to set alternate background color for tableview cell with sections

I use below code for setting background color in cells
if (indexPath.item % 2) {
// odd
[cell setBackgroundColor:[UIColor blueColor]];
} else {
// even
[cell setBackgroundColor:[UIColor whiteColor]];
}
This works ok if section has even number of rows, but if odd then two adjoining cells have the same color ( I have several setions).
I have no idea how to correct this.
Try with indexPath.row:
if (indexPath.row % 2) {
// odd
[cell setBackgroundColor:[UIColor blueColor]];
} else {
// even
[cell setBackgroundColor:[UIColor whiteColor]];
}
In cellForRowAt simply call one line:
cell.backgroundColor = indexPath.row % 2 == 0 ? .blue : .white
hope this help :)
You can also use this
static BOOL isEven = YES;
if(isEven) {
[cell setBackgroundColor:[UIColor blueColor]];
}
else {
[cell setBackgroundColor:[UIColor whiteColor]];
}
isEven = !isEven;

Change label background color...first red, then yellow on second click

I cannot find anything relating to it. I'm a beginner but I'm assuming that I need a NSArray to change the colors.
Anyway, I have a button and when you click the button once it changes a label background to GREEN. How do I make it so the first click it changes the label background to green...and then the second click it changes the background to YELLOW
- (IBAction)studentOne:(id)sender {
_studentOne.backgroundColor = [UIColor greenColor];
_studentOne.backgroundColor = [UIColor yellowColor];
_studentOne.backgroundColor = [UIColor redColor];
_studentOne.backgroundColor = [UIColor blackColor];
_studentOne.backgroundColor = [UIColor whiteColor];
}
That would be my sequence.
Would it be something involving
NSArray *colorArray;
colorArray = [NSArray array with objects:
I tried this because I thought it may be like changing text color on a button click
- (IBAction)studentOne:(id)sender {
NSArray *colorArray;
colorArray = [NSArray arrayWithObjects:
#"_studentOne.backgroundColor = [UIColor greenColor]",
#"_studentOne.backgroundColor = [UIColor yellowColor]",
#"_studentOne.backgroundColor = [UIColor redColor]",
#"_studentOne.backgroundColor = [UIColor blackColor]",
#"_studentOne.backgroundColor = [UIColor whiteColor]",
nil];
}
You're right about the array, a little off on the syntax. Something like this will work:
- (IBAction)studentOne:(id)sender {
static NSArray *colors;
if (!colors) colors = #[[UIColor redColor], [UIColor greenColor], [UIColor yellowColor]];
UIColor *currentColor = myLabel.backgroundColor;
NSInteger index = [colors indexOfObject:currentColor];
index = (index == NSNotFound || index == colors.count-1)? 0 : index+1;
self.myLabel.backgroundColor = colors[index];
}

Alternate between 3 colors in UITableviewCell

I have a UITableView that I would like to display in 3 different background colors. Basically white, light gray, dark gray, then back to white and so on.
This is all I have been able to find on stack overflow so far:
if (indexPath.row % 2) {
cell.contentView.backgroundColor = [UIColor lightGrayColor];
} else {
cell.contentView.backgroundColor = [UIColor darkGrayColor];
}
This works perfect for 2 colors. How can I alternate between 3 colors?
Just use 3 instead of 2 and then set the values accordingly, e.g.:
NSInteger colorIndex = indexPath.row % 3;
switch (colorIndex) {
case 0:
cell.contentView.backgroundColor = [UIColor whiteColor];
break;
case 1:
cell.contentView.backgroundColor = [UIColor lightGrayColor];
break;
case 2:
cell.contentView.backgroundColor = [UIColor darkGrayColor];
break;
}
You can also use [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] with whatever numeric values you want if you want a more shades of gray (e.g. 50).
Rob is correct but i will use default color provided by UIColor:
NSInteger colorIndex = indexPath.row % 3;
switch (colorIndex) {
case 0:
cell.contentView.backgroundColor = [UIColor whiteColor];
break;
case 1:
cell.contentView.backgroundColor = [UIColor lightGrayColor];
break;
case 2:
cell.contentView.backgroundColor = [UIColor darkGrayColor];
break;
}
Try this:
if(indexPath.row % 3 ==0){
cell.contentView.backgroundColor = [UIColor whiteColor];
}
if((indexPath.row-1) % 3 ==0){
cell.contentView.backgroundColor = [UIColor lightGrayColor];
}
if((indexPath.row - 2) % 3 ==0){
cell.contentView.backgroundColor = [UIColor darkGrayColor];
}

Resources