2009-08-11 59 views
9

我已經子類UIActionSheet,並且在-init方法中,我必須在調用超級init(無法傳遞var_args)後單獨添加按鈕。UIActionSheet addButtonWithTitle:不以正確的順序添加按鈕

現在,它看起來像這樣:

if (self = [super initWithTitle:title delegate:self cancelButtonTitle:cancel destructiveButtonTile:destroy otherButtonTitles:firstButton,nil]) { 
    if (firstButton) { 
    id buttonTitle; 
    va_list argList; 
    va_start(argList, firstButtton); 
    while (buttonTitle = va_arg(argList, id)) { 
     [self addButtonWithTitle:buttonTitle] 
    } 
    va_end(argList); 
    } 
} 
return self; 

然而,我在這種情況下,具體的使用有沒有破壞性的按鈕,一個取消按鈕和其他四個按鈕。當它出現時,順序是全部關閉,顯示爲

Button1的
取消
Button2的
將Button3

像他們只是添加到列表中,這是有道理的結束;但是,我不想看起來像這樣;那麼我該怎麼做?實際上,是否有任何方法可以正確地子類別UIActionSheet,並使其工作?

回答

21

您可以按正確順序添加它們,然後手動設置cancelButtonIndexdestructiveButtonIndex

對於您的代碼示例:正確,但不需要

if (self = [super initWithTitle:title delegate:self cancelButtonTitle:nil destructiveButtonTile:nil otherButtonTitles:nil]) { 
    if (firstButton) { 
    id buttonTitle; 
    int idx = 0; 
    va_list argList; 
    va_start(argList, firstButtton); 
    while (buttonTitle = va_arg(argList, id)) { 
     [self addButtonWithTitle:buttonTitle] 
     idx++; 
    } 
    va_end(argList); 
    [self addButtonWithTitle:cancel]; 
    [self addButtonWithTitle:destroy]; 
    self.cancelButtonIndex = idx++; 
    self.destructiveButtonIndex = idx++; 
    } 
} 
return self; 
+1

啊,這使得它更容易。我以爲那些是隻讀的 – 2009-08-11 19:11:49

+4

很好的答案,但櫃檯實際上是不必要的。 addButtonWithTitle:返回它添加的索引。 – 2010-07-21 01:24:03

8

阿維亞德本多夫的回答鍵索引計數器設置爲破壞並取消索引的索引。該addButtonWithTitle:方法返回新使用的按鈕的索引,所以我們可以使用該值馬上像這樣:

if (self = [super initWithTitle:title delegate:self cancelButtonTitle:nil destructiveButtonTile:nil otherButtonTitles:nil]) { 
    if (firstButton) { 
    id buttonTitle; 
    va_list argList; 
    va_start(argList, firstButtton); 
    while (buttonTitle = va_arg(argList, id)) { 
     [self addButtonWithTitle:buttonTitle] 
    } 
    va_end(argList); 
    self.cancelButtonIndex = [self addButtonWithTitle:cancel]; 
    self.destructiveButtonIndex = [self addButtonWithTitle:destroy]; 
    } 
} 
return self; 
+0

我認爲你的銷燬按鈕不在正確的位置。它應該在頂部。 – lhunath 2012-06-25 09:09:16

3

越早答案導致破壞性按鈕被放置在底部,這是不符合HIG,而且這對用戶來說也很混亂。破壞性的按鈕應該在頂部,取消在底部,其他人在中間。

以下命令他們正確:

sheetView   = [[UIActionSheet alloc] initWithTitle:title delegate:self 
             cancelButtonTitle:nil destructiveButtonTitle:destructiveTitle otherButtonTitles:firstOtherTitle, nil]; 
if (otherTitlesList) { 
    for (NSString *otherTitle; (otherTitle = va_arg(otherTitlesList, id));) 
     [sheetView addButtonWithTitle:otherTitle]; 
    va_end(otherTitlesList); 
} 
if (cancelTitle) 
    sheetView.cancelButtonIndex  = [sheetView addButtonWithTitle:cancelTitle]; 

參見https://github.com/Lyndir/Pearl/blob/master/Pearl-UIKit/PearlSheet.m用於實現(一個UIActionSheet包裝與基於塊的API)。