转载自:http://www.2cto.com/kf/201204/129090.html
在Windows应用程序中,经常使用模态(Model)对话框来和用户进行简单的交互,比如登录框。
在IOS应用程序中,有时我们也希望做同样的事情。但IOS的UI库中,没有模态对话框,最接近那个样子的应该算是AlertView。
但仅用AlertView,我们只能做文字提示,而不能和用户做交互。
本文将介绍如何基于AlertView做定制,实现模态对话框的功能。以密码修改框为例:
1. 首先,我们要继承AlertView类,在类的头文件PwdModifyView.h中,加入控件的声明
这里我们把控件都声明为property,目的是让外部的类可以访问用户输入的数据。
#import <UIKit/UIKit.h>
@interface PwdModifyView : UIAlertView {
// 旧密码输入框~
UITextField* _oldPwd;
// 新密码输入框~
UITextField* _newPwd;
// 新密码确认框~
UITextField* _cfmPwd;
}
@property (nonatomic, retain) UITextField* oldPwd;
@property (nonatomic, retain) UITextField* newPwd;
@property (nonatomic, retain) UITextField* cfmPwd;
@end
2. 在PwdModifyView.m文件中,需要实现两个函数
-(id) initWithTitle:(NSString*)title
message:(NSString*)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... {
self = [super initWithTitle:title
message:message
delegate:delegate
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:otherButtonTitles, nil];
if (self != nil) {
// 初始化自定义控件,注意摆放的位置,可以多试几次位置参数直到满意为止
// createTextField函数用来初始化UITextField控件,在文件末尾附上
self.oldPwd = [self createTextField:@"旧密码" withFrame:CGRectMake(22, 45, 240, 36)];
[self addSubview:self.oldPwd];
self.newPwd = [self createTextField:@"新密码" withFrame:CGRectMake(22, 90, 240, 36)];
[self addSubview:self.newPwd];
self.cfmPwd = [self createTextField:@"确认新密码" withFrame:CGRectMake(22, 135, 240, 36)];
[self addSubview:self.cfmPwd];
}
return self;
}
// Override 父类的 layoutSubviews 方法
-(void) layoutSubviews {
// 当 override 父类的方法时,要注意一下是否需要调用父类的该方法
[super layoutSubviews];
for (UIView* view in self.subviews) {
// 搜索AlertView底部的按钮,然后将其位置下移
// IOS5 以前按钮类是 UIButton, IOS5 里该按钮类是 UIThreePartButton
if ([view isKindOfClass:[UIButton class]] ||
[view isKindOfClass:NSClassFromString(@"UIThreePartButton")]) {
CGRect btnBounds = view.frame;
btnBounds.origin.y = self.cfmPwd.frame.origin.y + self.cfmPwd.frame.size.height + 7;
view.frame = btnBounds;
}
}
// 定义AlertView的大小
CGRect bounds = self.frame;
bounds.size.height = 260;
self.frame = bounds;
}
3. 当需要弹出该对话框时,只需创建并初始化一个PwdModifyView对象,然后调用对象的show()方法即可。
PwdModifyView* pwdModifyDlg = [[PwdModifyView alloc]
initWithTitle:@"密码修改"
message:nil
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:@"取消", nil];
[pwdModifyDlg show];
最后,附上UITextField的创建函数
-(UITextField*) createTextField:(NSString*)placeholder withFrame:(CGRect)frame {
UITextField* field = [[UITextField alloc] initWithFrame:frame];
field.placeholder = placeholder;
field.secureTextEntry = YES;
field.backgroundColor = [UIColor whiteColor];
field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
return field;
}