我在Kendall的答案和我的一個基本視圖控制器類中的塊的使用之間做了一個混合。現在,我可以使用AlertView和ActionSheets以提高可讀性。以下是我如何做到的:
在。我的ViewController h的我宣佈塊類型(可選,但建議報告)
typedef void (^AlertViewBlock)(UIAlertView*,NSInteger);
而且我宣佈一個可變dictionnary將存儲塊的每個alertview:
NSMutableDictionary* m_AlertViewContext;
在實現文件中我添加方法來創建AlertView並保存塊:
-(void)displayAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle withBlock:(AlertViewBlock)execBlock otherButtonTitles:(NSArray *)otherButtonTitles
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles: nil];
for (NSString* otherButtonTitle in otherButtonTitles) {
[alert addButtonWithTitle:otherButtonTitle];
}
AlertViewBlock blockCopy = Block_copy(execBlock);
[m_AlertViewContext setObject:blockCopy forKey:[NSString stringWithFormat:@"%p",alert]];
Block_release(blockCopy);
[alert show];
[alert release];
}
注意,我收到了相同的屬性UIAlertView中的構造函數,但委託(將作爲s精靈)。此外,我還收到一個AlertViewBlock對象,該對象保存在m_AlertViewContext可變詞典中。然後我會像通常那樣顯示警報。
在委託回調,我調用該塊,並給它的參數:
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
AlertViewBlock block = [m_AlertViewContext objectForKey:blockKey];
block(alertView,buttonIndex);
[m_AlertViewContext removeObjectForKey:blockKey];
}
- (void)alertViewCancel:(UIAlertView *)alertView {
NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
[m_AlertViewContext removeObjectForKey:blockKey];
}
現在,每當我需要使用AlertView我可以這樣調用:
[self displayAlertViewWithTitle:@"Title"
message:@"msg"
cancelButtonTitle:@"Cancel"
withBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"DO ACTION"]){
[self doWhatYouHaveToDo];
}
} otherButtonTitles:[NSArray arrayWithObject:@"DO ACTION"]];
我對ActionSheet也一樣,現在使用它們非常簡單。 希望它有幫助。
「地址應該在手機上保持不變」< - 這個地址是指向一個對象的指針,因此不能依賴它來保持常量。其餘的答案是明智的,我只是想指出這一點以備將來參考,以防其他人登陸此頁面。 – Morpheu5 2014-05-19 20:53:41