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

UITextView实现自动隐藏键盘,自动隐藏键盘

2012-06-04 18:29 239 查看
UITextView实现自动隐藏键盘
看了很多知名的帖子,没有找到我满意的。大多数都是自己写了按钮,没有实现自动隐藏的效果。在这里我自己歇了一个,实现了QQ聊天窗口的动画,公大家借鉴。
在头文件我们定义一个UITextView nameTextField
在.m文件里实现

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
这三个方法用来控制UITextView的内容效果
再实现下面三个触摸事件方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
用来控制键盘的重绘隐藏
鍵盤隱藏 键盘隐藏要注意的是触摸方法只能发生在UIView视图上,所以要定义一个来捕捉触摸的UIview视图,把这个视图设置成隐藏的,在需要他时显示,不需要隐藏。就能达到预期的效果。
这里提供一个demo的部分代码:
-(void)loadview
{
//会话表格显示主要内容的视图表格
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f,323.0f) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//cell风格,不要分隔
tableView.backgroundColor = [UIColor clearColor];// [UIColor colorWithRed:0.859f green:0.886f blue:0.929f alpha:1.0f];
tableView.tag = TABLEVIEWTAG;
[self.view addSubview:tableView];
[tableView release];
//捕捉触摸事件的遮罩层
UIView *myView1 = [[UIView alloc] initWithFrame:tableView.frame];
myView1.backgroundColor = [UIColor clearColor];//设置为透明
myView1.tag = MYVIEWS;
[self.view addSubview:myView1];
[myView1 release];

}
// 在开始编辑时打开遮罩层捕捉触摸事件,此时UITableView是不可见层
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// return NO to disallow editing.
UIView *col = (UIView *)[self.view viewWithTag:MYVIEWS];
[col setHidden:NO];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//当捕捉到触摸事件时,取消UITextField的第一相应
[nameTextField resignFirstResponder];
//重绘工作区域
UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:TOOLBARTAG];
toolbar.frame = CGRectMake(0.0f, 323.0f, 320.0f, 44.0f);//重绘放置UITextFeild的控件
UITableView *tableView = (UITableView *)[self.view viewWithTag:TABLEVIEWTAG];
tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, 323.0f);
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 响应完毕设置UIview隐藏
UIView *col = (UIView *)[self.view viewWithTag:MYVIEWS];
[col setHidden:YES];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// 设置UIview隐藏
UIView *col = (UIView *)[self.view viewWithTag:MYVIEWS];
[col setHidden:YES];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uiview 聊天 工作 qq
相关文章推荐