UIActionSheet addButtonWithTitle:不按正确的顺序添加按钮

Ed *_*rty 9 iphone cocoa-touch

我已经子类化了UIActionSheet,在-init方法中,我必须在调用super之后单独添加按钮init(不能传递var_args).

现在,它看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

但是,我在这种情况下的具体用途没有破坏性按钮,取消按钮和其他四个按钮.当它出现时,订单全部关闭,显示为

Button1
取消
Button2
Button3

就像他们被简单地添加到列表的末尾,这是有道理的; 但是,我不希望它看起来像这样; 那我该怎么办?事实上,是否有任何方法可以UIActionSheet正确地进行子类化并使其工作?

Avi*_*Dov 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;
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,但柜台实际上是不必要的.addButtonWithTitle:返回它添加的索引. (4认同)

Bra*_*Guy 8

Aviad Ben Dov的答案是正确的,但是不需要按钮索引计数器来设置销毁和取消索引的索引.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;
Run Code Online (Sandbox Code Playgroud)