如何在objective-c的pickerView中实现多次转换
Posted
技术标签:
【中文标题】如何在objective-c的pickerView中实现多次转换【英文标题】:How to implement a multiple conversions in pickerView in objective-c 【发布时间】:2019-12-09 15:18:01 【问题描述】:我正在尝试创建一个转换应用程序。我要转换三个单位:温度(华氏度、磅和英里到它们的公制对应物)。
我想使用选择器视图,但在将选择器视图连接到功能和实际选择每个单元时遇到了困难。
我已经能够在分段控件中实现这一点,但希望 pickerView 能够在未来添加更多转化。
谢谢!
ViewControlle.m
#import "ViewController.h"
@interface ViewController ()
NSArray *devices;
@end
//CONVERSIONS
// convert pounds to kilograms
double convertLbsToKgs(double poundsValue)
double kilogramsValue;
kilogramsValue = poundsValue / 2.205;
return kilogramsValue;
//convert fahrenheit to celcius
double convertFarenheitToCelcius(double farenheitValue)
double celciusValue;
celciusValue = (farenheitValue - 32) * 0.555;
return celciusValue;
//convert miles to kilometers
double convertMilesToKilometers(double milesValue)
double kilometersValue;
kilometersValue = milesValue * 1.609;
return kilometersValue;
@implementation ViewController
- (void)viewDidLoad
[super viewDidLoad];
devices = @[@"Pounds", @"Fahernheit", @"Miles"];
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
// pickerView datascource & delegate methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
return 1;
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
return devices.count;
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
return devices[row];
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
self.outputTextBox.text = devices[row];
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
@end
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *inputField;
@property (weak, nonatomic) IBOutlet UILabel *outputTextBox;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@end
【问题讨论】:
我已经实现了相同的代码,我没有任何问题。请简要描述发生了什么。 我可以显示当前启用了哪一行,但我想执行一些函数来计算华氏度到摄氏度等。 【参考方案1】:在 didselect 方法中添加此代码。
if ([devices[row] isEqualToString: @"Pounds"])
double kgs =[self convertLbsToKgs:[inputField.text doubleValue]];
outputTextBox.text=[NSString stringWithFormat:@"%f",kgs];
else if ([devices[row] isEqualToString: @"Fahernheit"])
double celcious =[self convertFarenheitToCelcius:[inputField.text doubleValue]];
outputTextBox.text=[NSString stringWithFormat:@"%f",celcious];
else if ([devices[row] isEqualToString: @"Miles"])
double kms=[self convertMilesToKilometers:[inputField.text doubleValue]];
outputTextBox.text=[NSString stringWithFormat:@"%f",kms];
【讨论】:
以上是关于如何在objective-c的pickerView中实现多次转换的主要内容,如果未能解决你的问题,请参考以下文章
如何在 PickerView 顶部添加一个按钮以及如何在单击该按钮时关闭 PickerView?
如何在键盘外观上向上移动包括pickerview在内的整个视图
使用 UITableViewController 时如何让 pickerView 粘在底部?