UITextView使用体会

UITextView跟UITextField很类似,不同的地方还是挺多的,例如没有placeholder,这个需要使用代理来进行设置,代码如下:

首先要UITxtViewDelegate;

代理方法:

首先在创建时候 我们要设置TextView的属性:

 textView.textColor = [UIColor graycolor];//placeholder的颜色

textView.text = @"请输入内容";//placeholder的内容

#pragma mark - TextField代理方法

- (void)textViewDidChange:(UITextView *)textView

{

    textView.textColor = titleCl;//输入文本的颜色

}

/**在开始编辑的代理方法中进行如下操作*/

- (void)textViewDidBeginEditing:(UITextView *)textView

{

    if ([textView.text isEqualToString:@"请输入内容"]) {

        textView.text = @"";

    }else{

        textView.textColor = titleCl;//输入文本的颜色

    }

 }

/**在结束编辑的代理方法中进行如下操作*/

- (void)textViewDidEndEditing:(UITextView *)textView

{

    if (textView.text.length<1) {

        textView.text = @"请输入内容";

        textView.textColor =  [UIColor graycolor];//placeholder的颜色

    }else{

        textView.textColor = titleCl;

    }

}

这样设置以后,就会出现类似textfield的placeholder效果;

 

由于textview的高度有时候我们设置很高的,当用户输入完毕以后,想关闭键盘的时候,我们可以在键盘弹起的时刻,给他加一个关闭选项,QQ聊天输入框就是这种效果

UIView *keyBoardTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 44)];

    keyBoardTopView.backgroundColor = [UIColor lightGrayColor];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(keyBoardTopView.bounds.size.width - 60 - 12, 4, 60, 36)];

    [btn setTitle:@"关闭" forState:UIControlStateNormal];

    btn.titleLabel.font = [UIFont systemFontOfSize:16];

    [btn addTarget:self action:@selector(writedone:) forControlEvents:UIControlEventTouchUpInside];

    [keyBoardTopView addSubview:btn];

    textview.inputAccessoryView = keyBoardTopView;

- (void)writedone//关闭键盘

{

  [self.view endEditing:YES];

}

原文地址:https://www.cnblogs.com/blogfantasy/p/4819217.html