最近寫了一個自定義的對話框
的demo,想模仿系統的UIAlertView的實現方式,對處理可變參數
的時候,遇到了小問題,於是谷歌了一下,寫下了處理問題的方法,記錄下來,以備後需。
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... {
if (self = [super init]) {
self.title = title;
self.delegate = delegate;
self.frame = CYScreen.bounds;
// 獲取可變參數的值
if (![self isBlankString:cancelButtonTitle]) {
[self.buttonTitles addObject:cancelButtonTitle];
}
NSString *str;
va_list list;
if(otherButtonTitles)
{
// 1.取得第一個參數的值
CYLog(@%@, otherButtonTitles);
[self.buttonTitles addObject:otherButtonTitles];
// 2.從第2個參數開始,依此取得所有參數的值
va_start(list, otherButtonTitles);
while ((str = va_arg(list, NSString *))){
CYLog(@%@, str);
[self.buttonTitles addObject:str];
}
va_end(list);
}
CYLog(@%@, self.buttonTitles);
}
return self;
}
- (IBAction)showDialog {
CYAlertView *alert = [[CYAlertView alloc]initWithTitle:@我的提示 message:@消息正文 delegate:self cancelButtonTitle:@取消 otherButtonTitles:@確定, @XXX, @YYY, nil];
alert.containerView = [self createDemoView];
[alert show];
}
2015-07-06 15:54:26.422 CYCustomAlertView[358:42937] 確定
2015-07-06 15:54:26.424 CYCustomAlertView[358:42937] XXX
2015-07-06 15:54:26.424 CYCustomAlertView[358:42937] YYY
2015-07-06 15:54:26.425 CYCustomAlertView[358:42937] (
取消,
確定,
XXX,
YYY,
)