How to limit UILabel text using objective C? - ios

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];

Related

Is that integer equal to the number in textfield

I'm new to Xcode and Objective-C. I watched a tutorial where he compared a char with the entered text in the textfield of the simulator. He used the following code:
BOOL isUsersEqual = [self.username isEqualToString:[self.usernameTextField text]];
When trying to build a small app myself I have problems to get the number out of the Textfield and be processed into my code. I want it to compare the random number I generated to the number in the textfield. How can I accomplish that?
I know this is kind of a nooby question and I don't wanna ask every time. Is there someplace I can look up all those types of questions?
You can try it by converting the number into string and then comparing -
NSString *number = [self.username stringValue];
if(number isEqualToString:self.usernameTextField.text){
//Do Something
}
else{
//Do Something
}
But this method only works when you're comparing Equals To -
For Greater than/ Less than/Equal to you can try it by converting the textfield's text into number and then comparing -
NSNumber *number = [self.usernameTextField.text integerValue];
if(number == self.username){
//Do Something
}
else{
//Do Something
}
To compare your generated number with a number from textField, you must first typecast the textField text to NSInteger using
NSInteger b = [[textField text] integerValue];
then you can proceed to compare the 2 numbers.
To fully understand these types of questions, I recommend you learning about objective-c primitive types and typecasting. Good luck!

Assign uitableview cell based on dictionary valueForKey

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]])

NSMutableAttributedString will not display attribute that begins at nonzero index

UPDATE:
I created a really simple standalone project to demonstrate the bug. If anyone would like to pull same and see if they can spot where I've gone wrong, I'd sure appreciate it. There's not much code to look through. Public repo here:
https://github.com/reidnez/NSAttributedStringBugDemo
I'm having a very strange issue here: I have a tableview. Each cell has a title label with 1-3 words, and a keywords label with several CSV keywords. I also have a search bar. The requirement is that as the user types into the search bar, any partial matches on both the title and keywords for each cell are shown highlighted. Screenshots:
First image is A-Okay. In the second image, the "an" of the title label should be highlighted. But, as you can see, not so much...
This works perfectly fine on the "keywords" label, as you can see above. The attributed strings for both of these labels are created by a category I wrote (code below). The same method is called on both strings, and appears to behave the same from what the debugger is telling me. The UI tells a different story.
I have stepped through the debugger numerous times, and in all cases, the attributed string appears to have been configured correctly. I have also verified that something else is not calling [tableView reloadData] and that no other place in my code is overwriting the label's value. This is how matching on "an" for "Fang" looks in the debugger, just before the cell is returned at the end of cellForRowAtIndexPath:
(lldb) po customCell.entryTitleLabel.attributedText
F{
}an{
NSBackgroundColor = "UIDeviceRGBColorSpace 0.533333 0.835294 0.156863 1";
}g{
}
Looks good to me...that is exactly what I want. But when the cell renders, there are NO highlights to be seen! Weirder yet, as an experiment I tried setting the label to a completely arbitrary attributedString that I created right in cellForRow:
NSMutableAttributedString *fake = [[NSMutableAttributedString alloc] initWithString:#"Fang"];
[fake addAttribute:NSBackgroundColorAttributeName value:MATCH_TEXT_HILIGHT_COLOR range:NSMakeRange(1, 2)];
customCell.entryTitleLabel.attributedText = fake;
This, too fails. No highlighting at all...but I CAN highlight any substring in the range of {0, 1} to {0, fake.length} and it behaves as expected. Again, it seemingly refuses to highlight any substring that does not begin at index 0--but only for the title label.
Am I losing my mind? What am I missing?
Below is my category...but I am fairly confident the problem does not lie here, because it functions perfectly for the keywords string, and (again) the attributes appear to be set correctly just before the cell returns:
-(void)hilightMatchingSubstring:(NSString*)substring color:(UIColor*)hilightColor range:(NSRange)range
{
if ([self.string compare:substring options:NSCaseInsensitiveSearch] == NSOrderedSame) {
[self addAttribute:NSBackgroundColorAttributeName value:hilightColor range:NSMakeRange(0, self.length)];
return;
}
// Sanity check. Make sure a valid range has been passed so that we don't get out-of-bounds crashes. Default to return self wrapped in an attributed string with no attributes.
NSRange selfRange = NSMakeRange(0, self.length);
if (NSIntersectionRange(selfRange, range).length == 0) {
NSLog(#" \n\n\n*** Match range {%lu, %lu} does not intersect main string's range {%lu, %lu}. Aborting *** \n\n\n", (unsigned long)range.location, (unsigned long)range.length, (unsigned long)selfRange.location, (unsigned long)selfRange.length);
return;
}
if (substring.length > 0) {
NSRange movingRange = NSMakeRange(range.location, substring.length);
if (NSMaxRange(movingRange) > self.length) {
return;
}
NSString *movingString = [self.string substringWithRange:movingRange];
while (NSMaxRange(movingRange) < NSMaxRange(range)) {
if ([movingString compare:substring options:NSCaseInsensitiveSearch] == NSOrderedSame) {
[self addAttribute:NSBackgroundColorAttributeName value:hilightColor range:movingRange];
}
movingRange = NSMakeRange(movingRange.location + 1, substring.length);
movingString = [self.string substringWithRange:movingRange];
}
} // This is fine...string leaves properly attributed.
}
Thanks for writing this up... Thought I was going crazy too!
I came up with a workaround (read: hack) whilst we wait for something official from Apple.
NSDictionary *hackAttribute = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor clearColor], NSBackgroundColorAttributeName, nil];
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:#"some text..."];
[attributedAddressText setAttributes:hackAttribute range:NSMakeRange(0, attributedText.length)];
// Then set your other attributes as per normal
Hope that helps.

Adding label text together

Hi im relatively new to iOS and I'm just wondering how i would add two labels together.
- (IBAction)switch1
{
if (switch1.on) {
value1.text = #"3";
} else {
value1.text = #"0";
}
}
- (IBAction)switch2
{
if (switch2.on) {
value2.text = #"3";
} else {
value2.text = #"0";
}
}
As you can see i have used two switches which would show two different values if they were turned on or off.
Could someone help me understand how i would add two values together.
I.e if switch one was on and switch two was off the value would be three i want this value to be shown in another label.
So far i have come up with this but for some reason it doesn't work, i have a feeling it is the format specifier but I'm not sure.
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
Dont you have this:
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
in ViewDidLoad or something? Because you have to call this at the end of both IBActions. If you don't, your final value will never change.
Make sure you properly created an outlet connection in Interface Builder as described here:
Creating an Outlet Connection
In short words. Ctrl+Click & Drag from the UISwitch to File’s Owner and click the new switch1 or switch2 action. Create outlets for the text fields and switches and link them.
Set breakpoints in switch1 and switch2 methods and ensure there are being called.
Use po command in the console to check if the text fields and switches are configured correctly.
For example:
po _textField1
should print text field's description. It will print nil when the text field is not there - not linked to a control in interface builder.

iPhone - how to select from a collection of UILabels?

I have a few UILabels, any one of which will update according to the index of an NSArray index they represent. I thought of selecting them by their tag
self.displayLabel.tag = myArray[index];
but that changes the tag value to whatever my array is holding at the moment
Using a dictionary for whatever tricks it offers instead of an NSArray doesn't help because i still have to select the correct matching label. This is the effect i want to achieve.
self.|mySelectedLabel|.text = myArray[index];
what should i put in |mySelectedLabel| to get the one i'm looking for?
I'm almost ashamed to ask at my reputation level, but this is stymie-ing me
every search only turns up how to set Labels and change, not the process of selecting
Assuming you have set the tags to the appropriate index to match your
array indices you can use [self.view viewWithTag:index];
Why are you not setting the tag with:
self.displayLabel.tag = index;
Also, you could just loop though an array of labels and find the right one:
for (UILabel *label : labelArray) {
if (label.tag == index) {
label.text = #"I found you!";
}
}
Rather than using tags you can refer to your specific textfields by reference:
// Create an array to hold your textfields
NSMutableArray *textFields = [NSMutableArray array]
// Create your textfields and add them to the array
UITextField *textField;
for (NSUInteger idx = 0: idx++; idx < numberOfTextFieldsYouWant) {
textField = [UITextField alloc] initWithFrame:<whateverYouWant>];
[textFields addObject:textField];
}
Since you are adding the objects to an array, rather than using the tag value 0, 1, 2... you can just access it by it's index in the array
So, for what you want to do you can just do:
textfields[index].text = myArray[index];
It's a lot cleaner, doesn't rely on magic tags, and you have an array of all your dynamic textfields that you can remove, or change in one place.
I think tags are vastly overused, and they aren't necessary in most cases.
Just letting you know I reframed the problem and this eventually worked for me without having to use an array
( with endless experimenting, I sort of bumped into it so I don't know if it constitutes good technique )
the desired label corresponding to the bag weight ( one of a number possible ) displays the right update
- (IBAction)acceptWeight:(UIButton *)sender {
int tempValue = (int) currentWeight;
// current weight comes from a UISegementedController
for (UILabel *labels in self.view.subviews)
{
if (labels.tag == currentWeight)
{
bags[tempValue]++;
labels.text = [NSString stringWithFormat:#"%i",bags[tempValue]];
}
}
totalKilo = totalKilo + (int)currentWeight;
self.totalKilo.text = [NSString stringWithFormat:#"%d",totalKilo];
}

Resources