我已将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;
但是,我在这种情况下的具体用法没有破坏性按钮,取消按钮和其他四个按钮。当它出现时,订单全部关闭,显示为
Button1的
取消
BUTTON2
BUTTON3
就像他们被简单地添加到列表的末尾一样,这是有道理的;但是,我不希望它看起来像这样;那我该怎么办?事实上,是否有任何方法可以正确地继承UIActionSheet
并使其有效?
答案 0 :(得分:21)
您只需按正确的顺序添加它们,然后手动设置cancelButtonIndex
和destructiveButtonIndex
。
对于您的代码示例:
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 :(得分: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;
答案 2 :(得分: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了解实现(带有基于块的API的UIActionSheet包装器)。