前回に続きUIDatePickerについて。
UIDatePickerのUIDatePickerModeCountDownTimerの情報ってあんまりないよね。
こちらのサイトを参考にしました。
UIDatePickerModeCountDownTimerで値を設定/取得する方法 – colori
また、秒数と時間の変換は、こちらを参考にしました。
NSLog(@”%.2d時%.2d分%.2d秒”,hourTime,minutTime,secondTime);
前回のコードをちょっと変えてみました。
UIDatePickerModeCountDownTimerは分単位までで秒までいじれないのが残念。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
#import "ViewController.h" @interface ViewController ()<UITextFieldDelegate> @property (weak, nonatomic) IBOutlet UITextField *testText; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //デートピッカーのインスタンス作成初期化 UIDatePicker *datePicker= [[UIDatePicker alloc]init]; //デートピッカーのモードを設定 datePicker.datePickerMode = UIDatePickerModeCountDownTimer; //テキストフィールドの入力をデートピッカーに変更 _testText.inputView = datePicker; //ピッカーの値が変更された時に呼ばれるメソッドを設定 [datePicker addTarget:self action:@selector(datePicker_ValueChanged:) forControlEvents:UIControlEventValueChanged]; //テキスト入力のキーボードに閉じるボタンを付ける UIView* accessoryView =[[UIView alloc] initWithFrame:CGRectMake(0,0,320,50)]; accessoryView.backgroundColor = [UIColor clearColor]; // ボタンを作成する。 UIButton* closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; closeButton.frame = CGRectMake(self.view.frame.size.width-120,10,100,30); [closeButton setTitle:@"閉じる" forState:UIControlStateNormal]; // ボタンを押したときによばれる動作を設定する。 [closeButton addTarget:self action:@selector(closeKeyboard:) forControlEvents:UIControlEventTouchUpInside]; // ボタンをViewに貼る [accessoryView addSubview:closeButton]; //ボタンを適用するテキストフィールドに設定 _testText.inputAccessoryView = accessoryView; } //キーボードを閉じる -(void)closeKeyboard:(id)sender { [self.testText resignFirstResponder]; } //ピッカーの値を反映 - (void)datePicker_ValueChanged:(id)sender { UIDatePicker *datePicker = sender; int time = (int)[datePicker countDownDuration]; int secondTime = time%60; //秒 int minutTime = (time/60)%60; //分 int hourTime = (time/60/60); //時 self.testText.text = [NSString stringWithFormat:@"%.2d時間%.2d分%.2d秒",hourTime,minutTime,secondTime]; NSLog(@"%.2d時%.2d分%.2d秒",hourTime,minutTime,secondTime); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end |
UIDatePickerModeCountDownTimerの値は秒数で、countDownDurationプロパティに入ってる。
setCountDownDurationプロパティで数値をセットすることも出来ます。