有的时候开发往往需要使用到与textField相似但是又有些不同的控件textView.介绍一些常见用法
//MARK:修改键盘上返回按钮的状态
self.groupNameTextView.returnKeyType = UIReturnKeyDone;
//MARK:设置代理
self.groupManifestoTextView.delegate = self;
#pragma mark - textView设置与textField边框一样的灰色边框,可以试用与给所有的系统控件添加bian
- (void)changeTextView:(UITextView *)textView {
textView.layer.borderColor = [[UIColor colorWithRed:215.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1] CGColor];
textView.layer.borderWidth = 0.6f;
textView.layer.cornerRadius = 6.0f;
}
#pragma mark - 键盘退出的方法
(1)如果你程序是有导航条的,可以在导航条上面加多一个Done的按钮,用来退出键盘,当然要先实现UITextViewDelegate。
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *done = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(leaveEditMode)] autorelease];
self.navigationItem.rightBarButtonItem = done;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (void)leaveEditMode {
[self.textView resignFirstResponder];
}
2)如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。
#pragma mark - UITextView Delegate Methods
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
#pragma mark - 监听谈起退出两个通知,并且计算需要偏移的高度,然后动画偏移view
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//注册通知,监听键盘出现
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(handleKeyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
//注册通知,监听键盘消失事件
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(handleKeyboardDidHidden:)
name:UIKeyboardDidHideNotification
object:nil];
}
#pragma mark - 键盘遮挡问题
- (void)handleKeyboardDidShow:(NSNotification*)paramNotification
{
//获取键盘高度,在不同设备上,以及中英文下是不同的
CGFloat kbHeight = [[paramNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//计算出键盘顶端到inputTextView panel最大Y值(加上自定义的缓冲距离15),得到偏移量
CGFloat offset = CGRectGetMaxX(self.groupManifestoTextView.frame) - (self.view.frame.size.height - kbHeight) + 15;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[paramNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//将视图上移计算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
}
- (void)handleKeyboardDidHidden:(NSNotification*)paramNotification
{
// 键盘动画时间
double duration = [[paramNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//视图下沉恢复原状
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}
- (void)viewDidDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}