2 text fields to always equal 100 percent xcode - objective-c

I have two text fields that are for percentages to be entered in. If i put 20 in the first field I would like the second text field to be updated to 60. And later on if I changed the second one to say 30, I would like the first updated to 70.
For ease of showing what I mean, say I have two text fields _firstPercent and _secondPercent with associated labels _firstTotal and _secondTotal:
float firstPercent = [_firstPercent.text floatValue];
float firstAmount = (firstSalePercent / 100) * firstOrigonalAmount;
_firstTotal.text = [NSString stringWithFormat:#"%1.0f",firstAmount];
float secondPercent = [_secondPercent.text floatValue];
float secondAmount = (secondSalePercent / 100) * secondOrigonalAmount;
_secondTotal.text = [NSString stringWithFormat:#"%1.0f",secondAmount];
I really don't know how to handle this so I tried adding this below its respective code. It works for the first one, but not the second.
float percentToSecond = 100 - firstPercent;
_secondPercent.text = [NSString stringWithFormat:#"%1.0f", percentToSecond];
float percentToFirst = 100 - secondPercent;
_firstPercent.text = [NSString stringWithFormat:#"%1.0f", percentToFirst];
I have tried other solutions but don't know what to do.
I would just like someone to lead me in the right direction.
Thanks

How about using the delegate method controlTextDidEndEditing: to see what value was entered, and then set the value for the other text field. In the following code tf1 and tf2 are the IBOutlets for the two text fields.
-(void)controlTextDidEndEditing:(NSNotification *)obj {
float value = [[[obj.userInfo valueForKey:#"NSFieldEditor"] string] floatValue];
if (obj.object == self.tf1) {
self.tf2.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}else if (obj.object == self.tf2) {
self.tf1.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}
}
You'd have to do some more checking to make sure the user didn't enter a number greater than 100 or something not a number.

Related

objective-c- selecting items from a database based on a slider value?

I am trying to make a basic app that first brings you to a view controller with a slier, at the moment no matter what the slider value is it selects all from the database but I want the slider value to select all where the price is like the slider value.
I added this line to my code:
NSString *sql = [NSString stringWithFormat:#"select * from carPrices where price = %f", slider.value];
but it does not work, I get the error:
implicit conversion of an objective c pointer to 'const char*' is disallowed with ARC
I previously had the line saying const char *sql instead,
Please if anybody knows what I could be doing wrong could they please give me some advice.
EDIT
Ok so I managed to fix the error by adding this line:
NSString *SQLSTMNT = [NSString stringWithFormat:#"select * from carPrices where price = %f", slider.value];
const char * sql =[SQLSTMNT UTF8String];
but as the prices are very specific is there any way to get it to select prices like the one you chose?
Thanks,
MB.
Float values are hard to work with.
You cannot reliably check if two values are the same, so where price = %f is going to fail.
Instead, you need to do check a range of values:
CGFloat min = slider.value - 0.1;
CGFloat max = slider.value + 0.1;
NSString *sql = [NSString stringWithFormat:#"select * from carPrices where price > %f and price < %f", min, max];

Setting UILabel Text Multiple Times Within A Loop

I'm fooling around in XCode, trying to learn a little about the iOS SDK and Objective-C.
I have this for loop below, and it should print out several values to the screen (depending on the amount of months chosen), but instead, it's only printing out the final value.
Can anybody point out why?
Thanks a bunch, in advance!
for (int i = 1; i <= myMonthsDouble; i++)
{
myPaymentAmount = (myBalanceDouble/10) + myInterestDouble;
myBalanceDouble -= myPaymentAmount;
//convert myPaymentAmount double into string named myPaymentAmountString
NSString *myPaymentAmountString = [NSString stringWithFormat:#"%f", myPaymentAmount];
NSString *paymentInformation = [[NSString alloc] initWithFormat:#"%# months, %# per month.", monthsString, myPaymentAmountString];
myInterestDouble = (myBalanceDouble * (myInterestDouble/100))/12;
self.label.text = paymentInformation;
}
It is only printing the last value to the screen because you only have one label. Each time you get to the end of the loop, you are setting that label's text which is overriding the last value. If you want to print all of them to the screen, you will need to have either multiple labels or you will have to append the strings together and put them in either a label or a UITextView that is formatted so that they can all be seen (most likely a text view but it can be done with a label.)
One example of doing this would be:
label.text = [label.text stringByAppendingString:newString];
numLines++; //this starts at 0;
and then at the end:
label.numberOfLines = numLines;

Positive/Negative button not displaying properly

I am trying to add a positive/negative button onto a numerical input in a UItextfield, but I cannot get it to function properly. What I want it to do is just add or remove a negative sign from the front of the numerical input. I am able to do that, however I cannot find a method to maintain the original number of decimal places. This is what I have tried:
- (IBAction) negsign
{
float input = [userinput.text floatValue];
float result = ((input * (-1)));
negstring = [NSString stringWithFormat:
#"%f", result];
userinput.text = negstring;
}
With this I get just a string of zeros after, like -23.0000000. I've tried limiting the decimal places by changing to #"%.2f" but I dont want extra zeros for whole integers, or rounding more than 2 decimals places. I just want it to take something like 34.658939 or 23 and make it -34.658939 or -23. Does anyone have a method to do this?
What would work best in your case is the following code:
float input = [userinput.text floatValue];
float result = ((input * (-1)));
NSNumber *resultNum = [NSNumber numberWithFloat:result];
NSString *resultString = [resultObj stringValue];
userinput.text = resultString;
If you're trying to make the number negative instead of reversing the sign, it'd be better if you replace float result = ((input * (-1))); with float result = -ABS(input);
Really, the best way to handle this would be to never convert it from a string in the first place. Just replace the first character as needed like this:
- (IBAction) negsign
{
unichar firstCharacter = [userinput.text characterAtIndex:0];
if (firstCharacter == '-') {
// Change the first character to a + sign.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:#"+"];
} else if (firstCharacter == '+') {
// Change the first character to a - sign.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:#"-"];
} else {
// There is no sign so we assume that it is positive.
// Insert the - at the beginning.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 0)
withString:#"-"];
}
}

Issue with calculation

Can anyone see if there's problem with the way i handle the calculation below? I seemed to be getting "You scored 0" at runtime even when the answer is actually correct.
- (void)countGain{
int gain = 0;
int percentage;
if ([answer objectForKey:#"1"] == [usrAnswer objectForKey:#"1"]) {
gain += 1;
}
percentage = (gain / 10) * 100;
NSString *scored = [[NSString alloc] initWithFormat:#"You scored %d",percentage];
score.text = scored;
rangenans.text = [answer objectForKey:#"1"];
[scored release];
}
What is the point doing:
percentage = (gain / 10) * 100;
Use
percentage = gain * 10;
Rest looks good. You shouldn't divide integers. What if you get 3/10 and this is int value?
In condition change
if([answer objectForKey:#"1"] == [usrAnswer objectForKey:#"1"])
To:
if([[answer objectForKey:#"1"] isEqualToString:[usrAnswer objectForKey:#"1"]])
This is integer arithmetic. Try:
percentage = gain * 10;
or
percentage = (gain * 10 ) / 100;
or
percentage = ((float)gain / 10) * 100;
Note that in any of the above, you only have 10 options for the "percentage", so percentage = gain * 10; is the simpler.
The problem is that you are trying to compare NSStrings and == compares the assresses of strings. You want to compare their values
e.g.
NSString *correct = #"Yes";
NSString *answer = ..... from some entry;
Then these two NSStrings will point to different bits of memory.
to compre with the user replied you need to compare values using the isEqualToString: method
e.g.
gain += [correct isEqualToString:answer] ? 1 : 0;
In your code == failed each time so gain was always 0. So the int division problem never occureed - but it would have when gain became 1 etc.

NSNumber and decimal value

I have an NSNumber like this for example = 1978, i would like to convert this for : 1K9, seconde example : 35700 convert to : 35K7 ( where "k" is kilometers and "M" is meters, how i can do this
thanks
int temp;
NSNumber *yourNumber;//the number you enter from some where
NSString *newValue;
if([yourNumber intValue]>1000){
temp = [yourNumber intValue] % 1000 ;//your number module 1000
newValue= [[temp stringValue]stringByAppendingString:#"K"];
}
Note: I haven't my mac with me, if the [temp stringValue] gives any worning&error please inform me.
Here's how:
NSNumber *initialNumber = [NSNumber numberWithInt:35700];
NSString *resultString = [NSString stringWithFormat:#"%iK%i", floor(initialNumber / 1000), floor((initialNumber % 1000) / 100)];
Basically you can work with the internal number data.
Assuming you are working on a meter-based value, you might want something like this:
NSNumber *sourceValue = ... // your NSNumber value from any source
int meters = sourceValue.intValue;
int km = floor(meters / 1000); // only your kilometers
int sub_km = meters % 1000; // only the part behind the kilometers
int first_sub_km = floor(sum_km / 100); // the first digit of the subrange
NSString *readable = [NSString stringWithFormat:#"%iK%i", km, first_sub_km];
First, you split the meters into <= 1000 and > 1000.
Then you'll just have to put that out formatted, with a K in between.
Write your own subclass of NSNumberFormatter. In this subclass you can implement the calculation logic.
The logic might look like this.
Devide the value by thousend and add your "k"
if you want to have the first digit of hundreds get the thired last digit of your value
return the new string