IOS-UIAlertView和UIActionSheet

IOS中两大控件:UIAlertView和UIActionSheet

UIAlertView是在屏幕中央弹出一个消息框,该消息框可以用来做消息提示,也可以让用户选择不同选项。

UIActionSheet是在屏幕底端弹出一个消息框,功能类似UIAlertView,不过两者除了位置不一样外,其外观也有出入。为了能够响应UIAlertView和UIActionSheet,需要设定其代理,而对应的代理需要实现对应的协议(UIAlertViewDelegate,UIActionSheetDelegate)。实现以下两个函数

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;


示例代码

  • 代理实现协议
    @interface ViewController : UIViewController 

  • 主要功能代码
    -(IBAction)onTextFieldEnd:(id)sender
    {
        [_textTime resignFirstResponder];
        
    // 显示对话框
    #if 0
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"TextContend" message:_textTime.text delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Good", @"Thanks", nil];
        
        [alert show];
        [alert release];
    #else
        // 底部弹出对话框
        UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"ActionSheet" delegate:self cancelButtonTitle:@"cancelButtonTitle" destructiveButtonTitle:@"destructiveButtonTitle" otherButtonTitles:@"OtherButton1", @"OtherButton2", nil];
        
        [sheet showInView:self.view];
        [sheet release];
    #endif
    }
    
    // 按钮按下时响应函数
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        NSString* strInfo = nil;
        
        strInfo = [[NSString alloc] initWithFormat:@"你按下了【%@】按钮,第%d个按钮", [alertView buttonTitleAtIndex:buttonIndex], buttonIndex];
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"按钮响应代理函数" message:strInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        [strInfo release];
    }
    
    // 按钮按下时响应函数
    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        NSString* strInfo = nil;
        
        strInfo = [[NSString alloc] initWithFormat:@"你按下了【%@】按钮,第%d个按钮", [actionSheet buttonTitleAtIndex:buttonIndex], buttonIndex];
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"按钮响应代理函数" message:strInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        [strInfo release];
    }

你可能感兴趣的:(Objective-C,IOS开发)