若想做的比較合理,當然是要進一步判斷用戶是否確實填寫UITextField,沒填就鎖住(disable)UIAlertController的按鈕,有填才啟用(enable)按鈕
沒輸入文字 按鈕disable 有輸入文字 按鈕enable
UIAlertController設計如下
UIAlertController * alert = [UIAlertControlleralertControllerWithTitle:@"命名此對話"
message:@"請輸入文字為此對話命名"
preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.text = self.groupName;
textField.placeholder = @"群組名稱";
[textField addTarget:self action:@selector(groupNameChanged:) forControlEvents:UIControlEventEditingChanged];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:@"取消"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:@"確認"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
UITextField *textField = alert.textFields.firstObject;
// [略]取textField.text作後續使用
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:^{
[alert.textFields[0] becomeFirstResponder];
}];
依據文字輸入與否, 動態決定按鈕狀態的selector method
-(void)groupNameChanged:(UITextField *)textField {
UIResponder *responder = textField;
Class uiacClass = [UIAlertController class];
while (![responder isKindOfClass: uiacClass]) {
responder = [responder nextResponder];
}
UIAlertController *alert = (UIAlertController*) responder;
UIAlertAction *okAction = [alert.actions objectAtIndex:1];
NSString *inputString = textField.text;
inputString = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if(inputString.length == 0)
[okAction setEnabled:NO];
else
[okAction setEnabled:YES];
}
沒有留言:
張貼留言