温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

iPhone开源系列:UIAlertView-Block

发布时间:2020-06-19 20:24:02 来源:网络 阅读:4210 作者:benjielin 栏目:开发技术

      在iPhone项目开发的过程中,重新造轮子的事情屡见不鲜,一方面源于开发者的“自我”心态,但更多的是因为对开发项目的不了解。希望通过这样一个系列和大家一起发现和挖掘项目开发中常用的开源项目,共同改进iPhone应用开发。

     UIAlertView和UIActionSheet都采用了Delegate模式,在同一个视图控制器中使用多个UIAlertView或UIActionSheet时控制器需要同时充当它们的delegate,这种情况下处理函数中通常需要通过tag进行区分后处理。这样就经常会造成如下代码:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([alertView tag] == LOGIN_ERROR_ALERT) {    // it's alert for login error
        if (buttonIndex == 0) {     // and they clicked OK.
            // do stuff
        }
    }
    else if ([alertView tag] == UPDATE_ERROR_ALERT) {   // it's alert for update error
        if (buttonIndex == 0) {     // and they clicked OK.
            // do stuff
        }   
    }
    else {
    }
}

     这种针对tag的分支判断就会影响到代码可读性,并产生坏味道。UIAlertView-Block(https://github.com/jivadevoe/UIAlertView-Blocks)项目就可以克服这样的问题。该项目提供了可以使用代码块来处理按钮事件的UIAlertView和UIActionSheet的Category,示例代码如下:

RIButtonItem *cancelItem = [RIButtonItem item];
cancelItem.label = @"No";
cancelItem.action = ^
{
    // this is the code that will be executed when the user taps "No"
    // this is optional... if you leave the action as nil, it won't do anything
    // but here, I'm showing a block just to show that you can use one if you want to.
};

RIButtonItem *deleteItem = [RIButtonItem item];
deleteItem.label = @"Yes";
deleteItem.action = ^
{
    // this is the code that will be executed when the user taps "Yes"
    // delete the object in question...
    [context deleteObject:theObject];
};

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Delete This Item?" message:@"Are you sure you want to delete this really important thing?" cancelButtonItem:cancelItem otherButtonItems:deleteItem, nil]; [alertView show]; [alertView release];

 

   有了这样一个项目,是不是再次看到根据tag区分进行分支处理时会有一种重构的冲动呢?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI