Assign uitableview cell based on dictionary valueForKey - ios

I have a dictionary with valueForKey:#"point" and valueForKey:#"name". Only "name" is displayed in the tableview. When it populates the tableview I want to set each cell color according to the "point" value it has. This is dependent on how far off the "point" is from a 'total' value.
So, I start with setting the 'total' value by generating an array of objects, let's say "fruit", and take a count of the total objects in the array. Again, I want to compare how far off "point" is from that total number. Based on that difference:
-if it matches, make the cell color blue
-if it is one number less, make it green
-if it is two numbers less, make it red...
NSArray *fruit = [fruits valueForKey:#"fruitName"];
//total number of fruit
int equal = fruit.count;
NSString *isEqual = [#(equal) stringValue];
NSArray *isEqual2 = [isEqual componentsSeparatedByString:#""];
//total number of fruit minus one
int minusOne = fruit.count -1;
NSString *minusOne1 = [#(minusOne) stringValue];
NSArray *minusOne2 = [minusOne1 componentsSeparatedByString:#""];
//creating array of "point" from dictionary
NSArray *pointsArray = [self.points valueForKey:#"point"];
if ([pointsArray containsObject:isEqual]) {
cell.backgroundColor = [UIColor blueColor];
}
else if ([pointsArray containsObject:minusOne2]){
cell.backgroundColor = [UIColor greenColor];
}
It doesn't enter the statements to color the cells.
When I log 'pointsArray' I get the array (e.g. 4,1,1,1...).
When I log 'isEqual' I get the totalFruit number (e.g. 4).
I've also tried isEqualToArray with no luck. How can I assign each cell color?

Replace ([pointsArray containsObject:isEqual]) with:
([pointsArray containsObject:[isEqual stringValue]])
And replace ([pointsArray containsObject:minusOne2]) with:
([pointsArray containsObject:[minusOne2 stringValue]])

Related

Create Two UILabels dynamically using Objective C

In one array I have one string and one more array I want to display this dynamically in custom cell. My array structure is given below. It will change according to data coming from web service.
{
subDescription = (
"Worship Hours 5.00am to 12.30pm & 4.00pm to 10.00pm",
"The temple is open all days of the week"
);
subHeading = Hours;
}
And i tried like this using this format i can display subHeading Value only how to display subDescription array
float xCoordinate=10.0,yCoordinate=30.0,width=320,height=40;
float ver_space=20.0;
for (int i = 0; i <test.count; i++)
{
NSDictionary *lanuage=[test objectAtIndex:i];
NSString *work=[lanuage objectForKey:#"subHeading"];
NSArray *er=[lanuage objectForKey:#"subDescription"];
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake(xCoordinate,yCoordinate,width,height)];
label.text = work;
[events.contentView addSubview:label];
yTCoordinate=yTCoordinate+heightT+ver_space;
}
I am not sure that I understand, but why dont you use CollectionView instead of a label. There you can define header cell and sub cells. I think this fits your problem.
In case that you do not want to use collection view you can adjust your code and iterate with loop through your sub items array.
for (NSString *item in er) {
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake(xCoordinate,yCoordinate,width,height)];
label.text = item;
[events.contentView addSubview:label];
yCoordinate=yCoordinate+height+ver_space;
}

How to limit UILabel text using objective C?

I have created Tableview cell with custom UILabel. For this UILabel data, I am loading from NSMutableArray. NSMutableArray data loading from JSON. Now the problem is I need to limit the tableview cell UILabel text. Here below one example
Now :
-------------------------
12.132454556
-------------------------
Needed :
-------------------------
12.13
-------------------------
My Code :
pointbl.text = [NSString stringWithFormat:#"%#",[arraydata objectAtIndex:indexPath.row]];
Above tableview cell label data I need to show 5 digits only including ".". Some times NSMutableArray value will come "null", So based on that also I need to make some solution.
I have tried by using below code but, If my value "null" then its throwing exceptions.
temp = [[arraydata objectAtIndex:indexPath.row]stringValue];
if ([temp length] > 5) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 5}];
temp = [temp substringWithRange:range];
}
The simplest solution would be to add temp != nil to the if statement.
However, you may implement this in a different way. What's the type of the objects that are saved in arraydata? If's it a float value (and not a string, as can be concluded from your code samples), you can simply use NSNumberFormatter for the display. Even simpler, you can use: [NSString stringWithFormat:#"0.2f", floatValue] and it will give you at least most of what you're looking to achieve.
Try to convert to float:
if ([arraydata objectAtIndex:indexPath.row] != nil) {
pointbl.text = [NSString stringWithFormat:#"%.2f%%",[[arraydata objectAtIndex:indexPath.row]floatValue]];
}
else {
pointbl.text = #"0";
}
// as you are loading values from json so, it can have "null" value ("null" in string format, different from nil if object is empty)
float a = [yourValue floatValue];
label.text = [NSString stringWithFormat:#"%.2f",a];

How to check if table view cells subtitles are equal to each other iOS

I'm wondering if there is a way to check if a cell's detailTextLabel.text is equal to another cell's detailTextLabel.text.
The reason for this is I would like to set the detailTextLabel.textColor to the same color if the cells texts are equal to each other.
For instance, if there are multiple cells with the same subtitle - lets say I have three cells with a subtitle that say pizza - Id like to set the color for pizza to green.
I fear that adding my code might make things a bit more confusing, as I pull the subtitle from core data based on the user's search text (there's just alot going on as I also persist to core data from a data source). So the subtitles themselves are, in a way, random. My app essentially lets a user search for points of interests based on a category. So if the user searches for pizza, the map view will display any local restaurants that serve pizza. You're then able to save that specific point of interest and the subtitle is set to pizza (or whatever the user searched for). So it's possible to have multiple entries that have the subtitle pizza (if the user saves multiple points of interest based on the 'pizza'.)
Try and forget the logistics of setting the color, I'd really just like to know how I could check if the subtitles are equal to each other in a TableView. I should specify that we are not checking if the actual text is equal to a specific string:
Not:
if(cell.detailTextLabel.text == #"pizza"){
cell.detailTextLabel.textColor = randomColor;
}
Something like this
if(cell.detailTextLabel.text == some other detailTextLabel){
cell.detailTextLabel.textColor = randomColor;
}
Core Data Example
self.category is my NSManagedObject. In this case I've already been able to persist a randomly generated color to core data. All I really need is the logic to set the color equal to the subtitles that have also been persisted to core data.
-(void)configureCell:(CategoryTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{
//fetch record
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
self.category = [self.fetchedResultsController objectAtIndexPath:indexPath];
float red = [self.category.red floatValue];
float green = [self.category.green floatValue];
float blue = [self.category.blue floatValue];
UIColor *randomRGBColor = [[UIColor alloc] initWithRed:red green:green blue:blue alpha:1.0];
//update cell
[cell.textLabel setText:[record valueForKey:#"name"]];
cell.backgroundColor = randomRGBColor;
}
I think your approach is wrong. Why should you compare strings in cells rendered and not before it even started rendering. When you create your UITableView you have certain datasource, at least array of NSString (titles).
You can implement a render method in which you loop through the array of titles, find equals and create new array of NSDictionary for example, where for key #"title" you have your title and for key #"color" you have already calculated colour. And in your tableView:cellForRowAtIndex method you just get the colour from array and assign to UITableViewCell instance together with assigning text to detailTextLabel.
You could do something like this with a dictionary in your data layer, where you associate the subtitles with a specific color.
var dict = [String: UIColor]
...
if let color = dict[subtitle] {
//set the color of the cell
} else {
let newColor = //some color you haven't used yet
dict[subtitle] = newColor
}

I want to show objects of NSMutableArray in two different colors

There is an NSMutableArray "onlinevalarr" in which i have offline and online as values.
I want to show offline in red colour and online value in green colour.
This is my code:
{
for (NSString * str in onlinevalarr)
{
if ([str isEqualToString:#"online"])
{
NSLog(#"online");
cell.online.textColor = [UIColor greenColor];
}
else if ([str isEqualToString:#"offline"])
{
NSLog(#"offline");
cell.online.textColor = [UIColor redColor];
}
}
}
But with this code either i am getting all the values in red or all in green.
Think about what your code is doing.
You have a for loop that loops through ALL The elements in your array and sets the current cell's color based on on the current array element. As you go through your for loop you set the current cell's color to different values, and then once you're done, the cell will have the color for the last entry in your array. That doesn't make sense.
If this code is from your cellForRowAtIndexPath method, then you want to get the row of the current cell, use it as an index into your array, and then use that to determine the color for the current cell.
Try using different cell identifiers for each cell.
Ex: "OnlineCellIdentifier" and "OfflineCellIdentifier
After updating the colour, reload the data for that cell
I think this is what you are trying to do:
if ([(NSString*)[onlinevarr objectAtIndex:indexPath.row] isEqualToString:#"online"]){
NSLog(#"online");
cell.online.textColor = [UIColor greenColor];
}else if ([[(NSString*)[onlinevarr objectAtIndex:indexPath.row] isEqualToString:#"offline"]){
NSLog(#"offline");
cell.online.textColor = [UIColor redColor];
}
P.S. This code is to be kept in the cellForRowAtIndexPath method.
And please, don't just paste the code, understand it. This is the code-version of #DuncanC's answer.

Displaying Array in Text Label

I'm still sort of new to Xcode, so please be patient with me. Anyway, I'm having a bit of trouble trying to display the whole contents of an array in a UILabel. I'm able to display it by simply using the code
wordList.text = [NSString stringWithFormat:#"List of Words:\n %#", listA];
However upon running, the label ends up displaying a parenthesis and the words on their own lines, as well as quotation marks around the words, and the ending quotation mark and a comma in the line between each word. Example:
List of Words:
(
"apple
",
"banana
",
"etc.
While I do want the words to be displayed in their own lines, I do not want the parenthesis and the closing quotation mark and comma being displayed in a separate line. I would also prefer removing the parenthesis, quotation marks, and commas all together, but I wouldn't mind too much if I'm unable to.
Could anyone please explain why its being displayed as such, and to help me correctly display each word of an array in its own line in a UILabel?
Use this:
NSArray *listOfWords = #[#"One", #"Two", #"Three"];
NSString * stringToDisplay = [listOfWords componentsJoinedByString:#"\n"];
wordList.text = stringToDisplay;
Will Display:
One
Two
Three
The parentheses, quotation marks, and commas are being added because providing an array as an argument to the format specifier %# causes the -(NSString *)description method to be sent to the array. NSArray overrides NSObject's implementation of description and returns a string that represents the contents of the array, formatted as a property list. (As opposed to just returning a string with the array's memory address.) Hence, the extra characters.
You Can use this Code
NSArray *listOfWords = [NSArray arrayWithObjects:
#"one.",
#"two.",
nil];
for (NSString *stringToDisplay in matters)
{
//frame, setting
labelFrame.origin.x = 20.0f;
UILabel *stringToDisplayLabel = [[UILabel alloc] initWithFrame:labelFrame];
stringToDisplayLabel.backgroundColor = [UIColor clearColor];
stringToDisplayLabel.font = [UIFont boldSystemFontOfSize:12.0f];
stringToDisplayLabel.lineBreakMode = NSLineBreakByWordWrapping;
stringToDisplayLabel.numberOfLines = 0;
stringToDisplayLabel.textColor = [UIColor whiteColor];
stringToDisplayLabel.textAlignment = NSTextAlignmentLeft;
//set up text
stringToDisplayLabel.text = stringToDisplay;
//edit frame
[stringToDisplayLabel sizeToFit];
labelFrame.origin.y += stringToDisplayLabel.frame.size.height + 10.0f;
[self.view addSubview:stringToDisplayLabel];
[matterLabel release];
}

Resources