picker view - units conversion
I'm developing an application with a picker view that slide from the bottom (like an action sheet). I need to convert 3 units (litres, us gallons and imperial gallons). The value is taken from a text field but I don't know how to tell the compiler which was the unit to start from. (ie...the user insert the value in the the text field but if he changes the units (usg or ig), the value in the text field changes accordingly.
this is the array:
NSMutableArray *weightArray = [[NSMutableArray alloc] initWithObjects:@"", @"Ltr",@"Usg",@"Ig",
nil];
self.weightPickerViewArray = weightArray;
[weightArray release];`
this is the picker:
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (row == 1) {
labelVolume.text = [weightPickerViewArray objectAtIndex:row];
//more code here....
}else if (row == 2){
labelVolume.text = [weightPickerViewArray objectAtIndex:row];
//more code here....
}else if (row == 3){
labelVolume.text = [weightPickerViewArray objectAtIndex:row];
//more code here....
}开发者_开发百科 how can I tell the compiler which was the value before the selection?
Add a text indicating the units at the end of the string.
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (row == 1) {
NSString *initalValue = labelVolume.text;
// Do your calculations here based on unit
NSString *updatedValue = urNewValue;
labelVolume.text = updatedValue;
//more code here....
}else if (row == 2){
NSString *initalValue = labelVolume.text;
// Do your calculations here based on unit
NSString *updatedValue = urNewValue;
labelVolume.text = updatedValue;
//more code here....
}else if (row == 3){
NSString *initalValue = labelVolume.text;
// Do your calculations here based on unit
NSString *updatedValue = urNewValue;
labelVolume.text = updatedValue;
//more code here....
}
When you select a row in picker, it call's its delegate method pickerView:didSelectRow:inComponent: Here, you can can change the value of your text field depending on which row (liters, gallons, etc) user selected. Please refer the apple's class reference for UIPickerView delegate
If I understand your problem. You want catch event when user change units in your pickerView, pass the information to the view that contains text field and execute conversion.
So you can use NSNotificationCenter (documentation here). In your pickerView when value change put this code :
[[NSNotificationCenter defaultCenter] postNotificationName:@"unitValueChange" object:@"litres"];
In the view that contains UITextField put this code :
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethodToExecute:) name:@"unitValueChange" object:self];
Now when your PickerView launch notification your view launch this method :
-(void)myMethodToExecute:(NSNotification *)notif{
NSString *myUnitSelected = notif.object
}
精彩评论