2009-08-11 44 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)。

相关问题