So i have this slider in my view and that has a max of 13 and a min of 1. Dependent on how you move the slider the number changes and can be shown on a label that shows the current number the slider is on.
I want to be able to change the int from the slider into a string; so if the progress of the slider is 13 i want the label to read "A+", 12 with "A" 11 with "A-" and so on.
Without having to make 13 "if" statements because i have more than one slider, is there a way to make a method that checks the progress of the slider then converts the number to the desired letter grade?
here is my code for one of the sliders
-(IBAction)sliderChanged:(id)sender{
UISlider *slider = (UISlider *)sender;
int progress = (int)roundf(slider.value);
c1Grade.text = [NSString stringWithFormat:#"%d",progress];
}
// c1Grade is the label next to the slider showing the progress
Make an array of strings, and place the description at the index the description represents: #"A+" would be at index 13, "A" at index 12, and so on.
NSArray *gradeDescriptions = [NSArray arrayWithObjects: #"", #"F", #"D-", #"D", #"D+", #"C-", #"C", #"C+", #"B-", #"B", #"B+", #"A-", #"A", #"A+", nil];
NSString *descr = [gradeDescriptions objectAt:sliderPosition];
Since gradeDescriptions array never changes, you can initialize it once, and store in a static variable or an ivar.
Related
I have this code that uses DDUnitConverter for currency conversion.
#import "DDUnitConverter.h"
#import "DDCurrencyUnitConverter.h"
- (void) convertCurrency {
DDUnitConverter *converter = [DDUnitConverter currencyUnitConverter];
NSNumber *from = [NSNumber numberWithInt:42];
NSNumber *to = [converter convertNumber:from fromUnit:DDCurrencyUnitUKPoundSterling toUnit:DDCurrencyUnitUSDollar];
NSLog(#"new value: %#", to);
}
I want to set the fromUnit: and toUnit: arguments based on the user's selection. How should I do that?
DDCurrencyUnit is an enum (enumerated type). If you use a picker view for your user to pick a currency, you can use the selected row index for fromUnit and toUnit, as long as the rows in the picker are in the same order as they are in the enumeration.
For example, DDCurrencyUnitEuro is 0, DDCurrencyUnitJapaneseYen is 1, DDCurrencyUnitUKPoundSterling is 2 and so on. So if the first row of your picker view is "Euro", your second is "Japanese Yen", your third "UK Sterling" and so on, then the selected row index will correspond to the unit parameter.
Your example above is equivalent to
NSNumber *to = [converter convertNumber:from fromUnit:2 toUnit:3];
I've got a pop-up view that loads when a user clicks on a TableView with Core Data elements. On the pop-up view I have a label that represents an int value.
The pop-up view has two butons, one for decreasing the value of the label by 1 and one for increasing it by one. So + and -
What I want to do is to disable the minus button if the label's value is 0. What I've tried is:
-(void)viewDidLayoutSubviews{
NSString *daString = currentVal.text;
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:daString];
int number = [myNumber intValue];
if (number==0)
minus.enabled = NO;
else
minus.enabled = YES
}
The problem with my code is that the button stays disabled after I increase the label's value, and it's no longer equal to 0.
Any suggestions?
You should keep a reference to minus button e.g.
#property (strong, nonatomic) IBOutlet UIButton *minusButton;
Set it with a value of your minus button, or connect outlet in Interface Builder
in your action handler for plusButton, do something like that
-(IBAction)plusAction:(id)sender {
//Do your business logic
...
self.minusButton.enabled = YES;
}
//In your minusButton action handler
-(IBAction)minusAction:(id)sender {
//Do your business logic
...
NSString *daString = currentVal.text;
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:daString];
int number = [myNumber intValue];
if (number==0)
self.minusButton.enabled = NO;
else
self.minusButton.enabled = YES
}
It seems like you have things the other way around. I would take a totally different approach:
Keep an instance variable (which we'll call 'count') in this viewController which holds the number. it can be an NSInteger. now add a target (self) to both buttons with a #selector(buttonPressed:). now this is how this selector should look like:
- (void)buttonPressed:(id)sender{
if (sender==plusButton)
self.count++;
if (sender==minusButton)
self.count--;
label.text = [NSString stringWithFormat:#"%d",self.count];
minusButton.enabled = (self.count>0);
}
I would just do this with a UIStepper, instead of the 2 buttons. You can set properties right in your storyboard/IB file that specify the max and min, increments, and a bunch of other useful things too. There are a couple video tutorials posted on YouTube that probably cover everything you'll need to know to use it.
Also, I have noticed one thing that...
If the button in disabled state and you are trying to change the title of normal state, it wont work.
I had to change the state to enabled and then I could manipulate title and set back to disabled.
I currently use a UIStepper in a custom UITableViewCell hooked up to a UITextField to have people select how many items they want to add to their Shopping Cart.
To check if the object is in stock, I've got two numbers: The LocalStock and the TotalStock.
I want to do the following:
If the amount of objects falls into the local stock, I want the textfield the number is displayed in to turn green.
If the amount of objects falls into the supplier stock (so either there is no local stock, or the stepper value is higher than the local stock, so we need to get it from the supplier stock) turn the UITextField blue.
If neither the supplier stock nor local stock are sufficient, I want the textfield to turn yellow.
I got the following code:
- (IBAction)stepperValueChanged:(id)sender
NSLog(#"localstock: %#",localstock);
NSLog(#"TotalStock: %#",totalstock);
NSDecimalNumber *value = [NSDecimalNumber decimalNumberWithString: self.textField.text];
if (value <= localstock)
{
self.aantalTextField.backgroundColor = [UIColor greenColor];
NSLog(#"Value %# <= Localstock %# >GREEN< Totalstock: %#",value,localstock, totalstock);
}
else if (value <= totalstock)
{
self.aantalTextField.backgroundColor = [UIColor blueColor];
NSLog(#"Value %# <= totalstock %# >BLUE< Localstock: %#",value,totalstock,localstock);
}
else
{
self.aantalTextField.backgroundColor = [UIColor yellowColor];
NSLog(#"Value: %# LocalStock: %# TotalStock %# >YELLOW<",value,localstock,totalstock);}}
And it's not making much sense when I run it... Sometimes it catches the GREEN-statement, other times the BLUE, and sometimes the same value returns YELLOW.
Anyone care to take a look at this and show me where the (logical) error is?
Thanks in advance!
You are comparing objects, not their values. As long they are both of type NSDecimalNumber...you need to compare similar to this.
[value integerValue ] <= [localstock integerValue]
As far as I understood from your code, localstock, totalstock and value are objects, not integers and you are comparing objects pointers, not values.
Instead, you should use the
- (NSComparisonResult)compare:(NSNumber *)decimalNumber
declared in NSDecimalNumber class.
Or convert all to integers using for example
[value intValue]
I would like to have user click on a button to generate a ten-question quiz in the form of "a +/- b = c" where the values for a and b are from +10 to -10 and are randomly assigned for the ten questions. Also, the questions should randomly switch between addition and subtraction. How do I populate the plist file correctly? How do I use arc4random to create ten questions with random integers?
I thought it would be neat to have questions display in a one-column picker where user can scroll through the questions or just have text at a certain CGPoint on screen.
Instead, I have created a plist with 84 different possible questions and I want to randomly choose 10 from plist to create the quiz each time a user clicks on button. I have this so far:
NSString *plistFile = [[NSBundle mainBundle] pathForResource:#"global" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsofFile:plistFile];
NSLog(#"%#",[dict objectForKey:#"1"]);
NSLog(#"%#",[dict objectForKey:#"2"]);
NSLog(#"%#",[dict objectForKey:#"3"]);
global is the name of plist, #"1", #"2", #"3" etc are the names of the 84 diff Q's I put in plist. How do I randomly choose 10 of the 84 NSLogs?
Instead of using a NSDictionary, use NSArray if your keys are just numbers. You could then do
NSString *randomString = [array objectAtIndex:(arc4random() % [array count])];
to pick a random element.
However, I would really advice against looking it up in a plist if it's just different combinations of random numbers. Writing out all those combinations by hand is just a waste of time. That's what computers are for!
Old, but still relevant answer:
To generate a random number between -10and 10:
int a = (arc4random() % 21) - 10;
You could also make a function like this:
int randomIntegerInRange(int min, int max)
{
int range = max - min + 1;
return min + arc4random() % range;
}
Hi i'm creating a Keyframe animation from multiple images. My problem is i would like the animation to instantly change from one image to the next rather than a fade.
CALayer *animLayer = [CALayer layer];
animLayer.bounds = CGRectMake(0, 0, width, height);
animLayer.position = CGPointMake(0, 0);
CAKeyframeAnimation *customFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:#"contents"];
NSArray *sizeValues = [NSArray arrayWithObjects:(id)image1, (id)image2, nil];
NSArray *times = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.5f], nil];
NSArray *timingFunctions = [NSArray arrayWithObjects: [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault], nil];
[customFrameAnimation setValues:sizeValues];
[customFrameAnimation setKeyTimes:times];
customFrameAnimation.duration=5.0;
customFrameAnimation.beginTime = 1e-100;
customFrameAnimation.fillMode = kCAFillModeRemoved;
customFrameAnimation.timingFunctions = timingFunctions;
customFrameAnimation.removedOnCompletion = YES;
[animLayer addAnimation:customFrameAnimation forKey:nil];
Thanks in advance.
Your animation will need its calculationMode set to kCAAnimationDiscrete.
Take a look at the documentation on keyTimes which describes how the calculationMode is used:
The appropriate values in the keyTimes
array are dependent on the
calculationMode property.
If the calculationMode is set to
kCAAnimationLinear, the first value in
the array must be 0.0 and the last
value must be 1.0. Values are
interpolated between the specified key
times.
If the calculationMode is set
to kCAAnimationDiscrete, the first
value in the array must be 0.0.
If the
calculationMode is set to
kCAAnimationPaced or
kCAAnimationCubicPaced, the keyTimes
array is ignored.
If the values in the
keyTimes array are invalid or
inappropriate for the calculationMode,
the keyTimes array is ignored.
And then you can read the description of the calculation modes:
Value calculation modes
These constants are used by the
calculationMode property.
NSString * const kCAAnimationLinear;
NSString * const kCAAnimationDiscrete;
NSString * const kCAAnimationPaced;
Constants
kCAAnimationLinear
Simple linear
calculation between keyframe values.
Available in Mac OS X v10.5 and later.
Declared in CAAnimation.h.
kCAAnimationDiscrete
Each keyframe value is used in turn, no interpolated
values are calculated.
Available in
Mac OS X v10.5 and later.
Declared in CAAnimation.h.
kCAAnimationPaced
Keyframe values are interpolated to produce an even
pace throughout the animation.
Available in Mac OS X v10.5 and later.
Declared in CAAnimation.h.
In other words, the discrete calculation mode makes the animation jump to each key frame rather than animate/transition to it.
Best regards.