ios - 转发 UIAlertView 的可变参数

标签 ios objective-c c ios7 variadic-functions

我正在尝试设置一个非常简单的 UIAlertView,其中包含文本编辑、确定和取消按钮,我想根据文本编辑的内容禁用确定按钮。

为了能够保留委托(delegate),以便他不会在警报 View 之前离开(从而在用户对警报 View 执行某些操作时立即导致崩溃),我对其进行了子类化。现在,我希望能够将 otherButtonTitles 参数从我的 init 方法转发到 UIAlertView init 方法,但出于某些原因,只需这样做:

- (id)initWithTitle:(NSString *)title
            message:(NSString*)message
           delegate:(id /*<UIAlertViewDelegate>*/)delegate
  cancelButtonTitle:(NSString *)cancelButtonTitle
  otherButtonTitles:(NSString *)otherButtonTitles, ... {

    if (self = [super initWithTitle:title 
                            message:message 
                           delegate:delegate 
                  cancelButtonTitle:cancelButtonTitle 
                  otherButtonTitles:otherButtonTitles, nil]) {
        //stuff
    }

仅将 a​​rgs 的第一个元素添加到警报 View 。我发现我实际上可以使用以下方法将按钮手动添加到警报 View :

va_list args;
va_start(args, otherButtonTitles);
for (NSString *buttonTitle = otherButtonTitles; buttonTitle != nil; buttonTitle = va_arg(args, NSString*)) {
  [self addButtonWithTitle:buttonTitle];
}
va_end(args);

但是,我的 alertViewShouldEnableFirstOtherButton 委托(delegate)方法不再被调用,with the probable explanation in this post .

因此,我如何才能将我的 otherButtonTitles 正确转发到 UIAlertView 初始化方法?

最佳答案

那么让我们减少击键次数:

NSMutableArray *otherButtonTitles = [NSMutableArray array];
// .. collect varargs into ^^^

#define T(n) ([otherButtonTitles objectAtIndex:n])
#define CASE(n, ...) case n: self = [super initWithTitle:title \
                                                 message:message \ 
                                                delegate:delegate \
                                       cancelButtonTitle:cancelButtonTitle \
                                       otherButtonTitles:__VA_ARGS__, nil]; \
                             break

switch ([otherButtonTitles count]) {
    CASE(0, nil);
    CASE(1, T(0));
    CASE(2, T(0), T(1));
    CASE(3, T(0), T(1), T(2));
    // ... repeat until bored ...
    default: @throw @"too many buttons"; // or return nil
}

关于ios - 转发 UIAlertView 的可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26102660/

相关文章:

ios - 将 MKUserTrackingBarButtonItem 移动到导航栏的右侧

ios - GCDAsyncSocket 双向认证

ios - 使用 NSNotification 将消息从 UITableView 行选择传递到 uiViewController

c - UEFI 编程 : How to Initialize a CHAR16 Unicode String?

ios - 对象没有方法 'Status' iOS SDK和解析云代码

ios - 测试 CLGeocoder geocodeAddressString 方法地标始终为零

iphone - NSTimer 未按预期运行

objective-c - 从 AnyObject 转换时出错?到 SecKeyRef?在 swift

计算C文件代码部分的大小

c - 交换数组内的奇数和偶数,C