UIDatePickerModeCountDownTimer

前回に続きUIDatePickerについて。

UIDatePickerのUIDatePickerModeCountDownTimerの情報ってあんまりないよね。

こちらのサイトを参考にしました。
UIDatePickerModeCountDownTimerで値を設定/取得する方法 – colori
また、秒数と時間の変換は、こちらを参考にしました。
NSLog(@”%.2d時%.2d分%.2d秒”,hourTime,minutTime,secondTime);

前回のコードをちょっと変えてみました。
UIDatePickerModeCountDownTimerは分単位までで秒までいじれないのが残念。

iOS Simulator Screen Shot 2015.10.10 19.13.39

#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プロパティで数値をセットすることも出来ます。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です