您的位置:首页 > 产品设计 > UI/UE

IOS开发之自定义UIActionSheet

2012-06-01 20:35 337 查看
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


说明一下:customView就是可以自定义的区域,使用我这个自定义的类时,只要拿到customView,然后向其中addSubview即可,非常方便。customTitle就是上边栏的标题。这里带有一个初始化方法
-(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];
}


使用自定义控件的类,需要实现UIActionSheetDelegate协议。其中的函数:

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
做一些点击按钮后的操作。buttonIndex值为0,是点击“确定”按钮触发,1则是点击“取消”按钮后触发的。
这里我写了一个小例子,就是上面第一个图的内容,给出下载链接:

http://download.csdn.net/detail/ccf0703/4345682
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: