UIAlertView的自动消失,手动消失和自定制消失

来源:互联网 发布:农村淘宝手机版 编辑:程序博客网 时间:2024/04/29 16:25
UIAlertView的消失本质其实是触发了一个dismiss事件。

触发这个事件有以下两种方法:

1.按钮点击,UIAlertView上如果有按钮,点击任何按钮都会触发该事件,UIAlertView消失;

2.代码模拟点击

[java] view plaincopyprint?
  1. [AlertObject dismissWithClickedButtonIndex:0 animated:NO]  


1。创建一个自动消失的UIAlertView,这种消失方法的本质其实就是:使用定时器+代码模拟点击

[java] view plaincopyprint?
  1. -(void) performDismiss:(NSTimer *)timer  
  2. {  
  3. [Alert dismissWithClickedButtonIndex:0 animated:NO];  
  4. [Alert release];  
  5. }  
  6.   
  7. -(void)presentAlert  
  8. {  
  9. Alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"出错啦!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];  
  10.   
  11. [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];  
  12. [Alert show];  
  13. }  

2.手动消失

如果你的UIAlertView上有按钮的话,点击任何一个按钮,都会触发一个dismiss事件,引起UIAlertView的消失。

3.自定制的消失,其实就是在自己认为合适的时候模拟点击。

下面这个例子是在textField的delegate执行即点击returnKey且输入昵称合法的时候,UIAlertView消失。

[java] view plaincopyprint?
  1. - (void) enterNickName:(NSString*)msg  
  2. {  
  3. prompt = [[UIAlertViewalloc] initWithTitle:@"设置昵称"  
  4. message:msg  
  5. delegate:self  
  6. cancelButtonTitle:nil  
  7. otherButtonTitles:nil];  
  8.   
  9. UITextField *textField = [[UITextFieldalloc] initWithFrame:CGRectMake(27.0,70.0230.030.0)];  
  10. [textField setBackgroundColor:[UIColorwhiteColor]];  
  11. [textField setPlaceholder:@"输入昵称"];  
  12. textField.layer.cornerRadius=6.0;  
  13. textField.delegate=self;  
  14. textField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;  
  15. [prompt addSubview:textField];  
  16. [textField becomeFirstResponder];  
  17. textField.keyboardType=UIKeyboardTypeDefault;  
  18. textField.keyboardAppearance=UIKeyboardAppearanceDefault;  
  19. textField.returnKeyType=UIReturnKeyDone;  
  20. [textField release];  
  21. [promptsetTransform:CGAffineTransformMakeTranslation(0.0, -40.0)]; //可以调整弹出框在屏幕上的位置  
  22. [prompt show];  
  23. }  
  24.   
  25. #pragma textField delegate  
  26. - (BOOL)textFieldShouldReturn:(UITextField *)textField  
  27. {  
  28. NSLog(@"nickname=%@",textField.text);  
  29. if (nil==textField.text ||0==[[textField.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]] length])  
  30. {  
  31. prompt.message=@"\n\n昵称不能为空!";  
  32. return YES;  
  33. }  
  34. if ([[textField.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]] length]<2  
  35. ||[[textField.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]] length]>15)  
  36. {  
  37. prompt.message=@"\n\n昵称只支持2-15个字,请重新设置";  
  38. return YES;  
  39. }  
  40. [prompt dismissWithClickedButtonIndex:0animated:NO];//触发dismiss  
  41. [prompt release];  
原创粉丝点击