动态添加UIActionSheet按钮

来源:互联网 发布:淘宝产品拍照 编辑:程序博客网 时间:2024/05/17 21:40

UIActionSheet是一个非常有用的类,我就在应用中经常用它,但是它的初始化函数无法让你通过数组来添加按钮。通常你只能通过初始化参数来增加按钮——所有网络上的代码也几乎是使用该方法。
通常实现——硬编码按钮:
- (void)testActionSheetStatic {
// Create the sheet with buttons hardcoded in initialiser
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@”Static UIActionSheet”
delegate:self
cancelButtonTitle:@”Cancel”
destructiveButtonTitle:nil
otherButtonTitles:@”Item A”, @”Item B”, @”Item C”, nil];
[sheet showFromRect:view.bounds inView:view animated:YES];
[sheet release];
}

如果事先知道各个按钮并且再也不会改变的情况下,这样的实现是OK的。但如果我要在运行时改变应该怎么办呢?动态添加按钮看起来应该也很简单,不要init函数中指定而在之后添加可以了,如下代码就展示了这点。
- (void)testActionSheetDynamic {
// 创建时仅指定取消按钮
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@”Dynamic UIActionSheet” delegate:self
cancelButtonTitle:@”Cancel”
destructiveButtonTitle:nil
otherButtonTitles:nil];
// 逐个添加按钮(比如可以是数组循环)
[sheet addButtonWithTitle:@”Item A”];
[sheet addButtonWithTitle:@”Item B”];
[sheet addButtonWithTitle:@”Item C”];
[sheet showFromRect:view.bounds inView:view animated:YES];
[sheet release];
}

动态添加按钮(取消按钮也是动态添加的):
- (void)testActionSheetDynamic {
// 创建时不指定按钮
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@”Dynamic UIActionSheet” delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
// 逐个添加按钮(比如可以是数组循环)
[sheet addButtonWithTitle:@”Item A”];
[sheet addButtonWithTitle:@”Item B”];
[sheet addButtonWithTitle:@”Item C”];
// 同时添加一个取消按钮
[sheet addButtonWithTitle:@”Cancel”];
// 将取消按钮的index设置成我们刚添加的那个按钮,这样在delegate中就可以知道是那个按钮
// NB - 这会导致该按钮显示时有黑色背景
sheet.cancelButtonIndex = sheet.numberOfButtons-1;
[sheet showFromRect:view.bounds inView:view animated:YES];
[sheet release];
}

这样取消按钮就显示在底部并且行为也符合预期了。
对我来说现在剩下的最大一个疑问就是destructive按钮到底是什么(Apple文档也没有清晰地说明这点)?一些实验结果也表明它实际上和取消按钮并无区别,只不过它有一个红色背景而不是黑色的。所有如果在上例中改变destructiveButtonIndex而不是cancelButtonIndex,就可以看到标有“取消”的按钮有红色背景了。
出于完整性的考虑,和上述代码相匹配的delegate代码如下:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.cancelButtonIndex)
{ return; }
switch (buttonIndex)
{
case 0: {
NSLog(@”Item A Selected”);
break;
}
case 1: {
NSLog(@”Item B Selected”);
break;
}
case 2: {
NSLog(@”Item C Selected”);
break;
}
}
}

0 0
原创粉丝点击