今回は、管理系アプリでよく見る”テキストフィールド”を含んだアラートの実装をしてみました。
テキストフィールド付きアラートを作成
UIAlertActionのように、アラートコントローラー作成時に追加できるようです。
UIAlertController *aleartController =
[UIAlertController
alertControllerWithTitle:@"タイトル"
message:@"メッセージ"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelButton =
[UIAlertAction
actionWithTitle:@"キャンセル"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"キャンセル");
}];
UIAlertAction *saveButton =
[UIAlertAction
actionWithTitle:@"保存"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"保存");
}];
// アラートアクションを追加
[aleartController addAction:cancelButton];
[aleartController addAction:saveButton];
// アラート内にテキストフィールドを追加
[aleartController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"テキスト入力してください。";
// デリゲートを宣言
textField.delegate = self;
}
];
// アラートコントローラーを表示
[self presentViewController:aleartController animated:true completion:nil];
デリゲートメソッドの使用
アラート作成時にデリゲートを宣言することで使用できます。
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSLog(@"テキストを変更しました。");
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSLog(@"テキストの編集を完了しました。");
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(@"テキストの編集を開始しました。");
}
独自のメソッドを追加
デリゲートメソッドとは別に、テキストフィールドに独自のメソッドも設定できます。
テキストフィールド作成時に設定します。
// アラート内にテキストフィールドを追加
[aleartController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"テキスト入力してください。";
// デリゲートを宣言
textField.delegate = self;
// テキストフィールドにメソッドを設定することも可能
[textField addTarget:self action:@selector(didChangeTextField:)
forControlEvents:UIControlEventEditingChanged];
[textField addTarget:self action:@selector(didBeginEditingTextField:)
forControlEvents:UIControlEventEditingDidBegin];
[textField addTarget:self action:@selector(didEndEditingTextField:)
forControlEvents:UIControlEventEditingDidEnd];
}
];
設定したメソッド
- (void)didChangeTextField:(UITextField *)sender {
NSLog(@"テキストを変更しました。");
}
- (void)didEndEditingTextField:(UITextField *)sender {
NSLog(@"テキストの編集を完了しました。");
}
- (void)didBeginEditingTextField:(UITextField *)sender {
NSLog(@"テキストの編集を開始しました。");
}
まとめ
アラートコントローラーは使用頻度が多いので、使い方のバリエーションを増やしていきたいです。