在IOS应用程序中,有时我们也希望做同样的事情。但IOS的UI库中,没有模态对话框,最接近那个样子的应该算是AlertView。
但仅用AlertView,我们只能做文字提示,而不能和用户做交互。
本文将介绍如何基于AlertView做定制,实现模态对话框的功能。以密码修改框为例:
1. 首先,我们要继承AlertView类,在类的头文件PwdModifyView.h中,加入控件的声明
这里我们把控件都声明为property,目的是让外部的类可以访问用户输入的数据。
#import <UIKit/UIKit.h>
@interface PwdModifyView : UIAlertView
@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 {
[super layoutSubviews]; // 当override父类的方法时,要注意一下是否需要调用父类的该方法
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()方法即可。
PwdModifyDlg* 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;
}
摘自 linear