问题
I'm trying to set up a very simple UIAlertView
with a text edit, an Ok and a cancel button, and I want to disable the Ok button based on the content of the text edit.
To be able to retain the delegate so that he doesn't go away before the alert view (and thus cause a crash as soon as the user does something with the alert view), I've subclassed it. Now, I want to be able to forward the otherButtonTitles
argument from my init method to the UIAlertView
init method, but for some reasons, simply doing that:
- (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
}
only adds the first element of the args to the alert view. I've found that I can actually manually add the buttons to the alert view using this:
va_list args;
va_start(args, otherButtonTitles);
for (NSString *buttonTitle = otherButtonTitles; buttonTitle != nil; buttonTitle = va_arg(args, NSString*)) {
[self addButtonWithTitle:buttonTitle];
}
va_end(args);
but then, my alertViewShouldEnableFirstOtherButton
delegate method isn't called anymore, with the probable explanation in this post.
Thus, how can I forward correctly my otherButtonTitles
to the UIAlertView
init method correctly?
回答1:
Let's reduce keystrokes then:
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
}
来源:https://stackoverflow.com/questions/26102660/forward-variadic-arguments-for-a-uialertview