UIActionSheet动态添加按钮

上次谈到了 UIActionSheet的使用,今天说说动态添加UIActionSheet按钮。

一、UIActionSheet的通常实现方法:

- (void)testActionSheetStatic {
	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];
}

运行下就发现问题很明显——取消按钮是在视图的顶部,而标准做法是显示在底部。怎么解决呢?如果在init函数中添加取消按钮就无法解决了。最后找到了一种将取消按钮也动态添加。

- (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中就可以知道是那个按钮
	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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值