IOS开发中,经常会用到UIActionSheet,但是,默认的只能添加按钮。如果能自定义的话,岂不是更好?上网搜了一下,都是只有那一种代码,通过设置几个按钮来增加UIActionSheet的高度,不是很准确。今天研究了一下,然后做了一个可以自定义高度和控件的通用UIActionSheet,拿出来共享一下。
自定义UIActionSheet的思路就是写一个继承了UIActionSheet的类,然后重写里面的layoutSubviews函数。我写的自定义的布局就是在上方有一个navgationbar的区域,里面有左右两个按钮和一个title。下方是一个自定义区域。效果如下图(这个图里,自定义区域用了一个UIDatePicker):
自定义类的类名为CustomActionSheet。头文件如下:
#import <UIKit/UIKit.h> @interface CustomActionSheet : UIActionSheet @property (nonatomic, retain) UIView *customView; @property (nonatomic, retain) NSString *customTitle; -(id)initWithViewHeight:(float)_height WithSheetTitle:(NSString *)_title; @end
-(id)initWithViewHeight:(float)_height withSheetTitle:(NSString *)_title_title赋值给customTitle,_height就是自定义UIActionSheet中自定义区域的高度,对应上边的图,就是UIDatePicker所占区域的高度,自定义区域宽为320,不需要设置.
然后是CustomActionSheet.m文件,核心的代码就是重写的layoutSubviews函数,代码如下:
-(void)layoutSubviews{ [super layoutSubviews]; // // CGRect newFrame = self.frame; //// newFrame.origin.y = 459; // newFrame.origin.y = 459 - customViewHeight - NavBarHeight; // self.frame = newFrame; UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, ViewHeight - customViewHeight -NavBarHeight, 320, NavBarHeight)]; navBar.barStyle = UIBarStyleBlackOpaque; UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:self.customTitle]; UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(docancel)]; navItem.leftBarButtonItem = leftButton; UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(done)]; navItem.rightBarButtonItem = rightButton; NSArray *array = [[NSArray alloc] initWithObjects:navItem, nil]; [navBar setItems:array]; [self.superview addSubview:navBar]; [self.superview addSubview:self.customView]; }
- (void) done{ [self dismissWithClickedButtonIndex:0 animated:YES]; [self.delegate actionSheet:self clickedButtonAtIndex:0]; } - (void) docancel{ [self dismissWithClickedButtonIndex:1 animated:YES]; [self.delegate actionSheet:self clickedButtonAtIndex:1]; }
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
做一些点击按钮后的操作。buttonIndex值为0,是点击“确定”按钮触发,1则是点击“取消”按钮后触发的。
这里我写了一个小例子,就是上面第一个图的内容,给出下载链接:
http://download.csdn.net/detail/ccf0703/4345682