iphone 的UITextField 模仿百度搜索提示,达到输入正确E-mail地址,详细实现如下:
#import <UIKit/UIKit.h>
@interface DemoMailViewController : UIViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
{
UITextField *mailTextField;
UITableView *myTableView;
NSMutableArray *promptarray;
NSMutableArray *myArr;
}
@property (nonatomic,retain) IBOutlet UITextField *mailTextField;
@property (nonatomic,retain) IBOutlet UITableView *myTableView;
@property (nonatomic,retain) NSMutableArray *myArr;
-(IBAction) textFieldDoneEditing:(id)sender;
@end
#import "DemoMailViewController.h"
@implementation DemoMailViewController
@synthesize mailTextField,myTableView;
@synthesize myArr;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
myTableView.hidden=YES;
[super viewDidLoad];
}
-(IBAction) textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
//文本框开始输入的时候
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
self.myArr=[[NSMutableArray alloc] init];
[mailTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
//结束输入的时候
-(void)textFieldDidEndEditing:(UITextField *)textField
{
myTableView.hidden=YES;
}
//显示提示的选项
- (void) textFieldDidChange:(UITextField *) TextField
{
myTableView.hidden=YES;
promptarray=[[NSArray alloc]initWithObjects:@"@qq.com",@"@163.com",@"@gmail.com",@"@sina.com",@"@foxmail.com",@"@sohu.com",@"@163.com",@"@tom.com",@"@yeah.com",@"@yahoo.com.cn",nil];
[self.myArr removeAllObjects];
int i;
for(i=0;i<[promptarray count];i++)
{
NSMutableString *add=[[NSMutableString alloc] initWithString:TextField.text];
[add appendString:[promptarray objectAtIndex:i]];
[self.myArr addObject:add];
}
myTableView.hidden=NO;
[myTableView reloadData];
}
////随便点击外面刷新试图
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[mailTextField resignFirstResponder];
}
#pragma mark tableView delegate and dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.myArr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 48;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row=[indexPath row];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (myArr&&[myArr count])
{
cell.textLabel.text =[myArr objectAtIndex:row];;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
mailTextField.text = [myArr objectAtIndex:indexPath.row];
myTableView.hidden=YES;
}