--------UITextView用法总结
1.基本用法
self.textView=[[[UITextView alloc] initWithFrame:self.view.frame] autorelease]; //初始化大小并自动释放
self.textView.textColor = [UIColor blackColor];//设置textview里面的字体颜色
self.textView.font = [UIFont fontWithName:@"Arial"size:18.0];//设置字体名字和字体大小
self.textView.delegate = self;//设置它的委托方法
self.textView.backgroundColor = [UIColor whiteColor];//设置它的背景颜色
self.textView.text = @"abcdefgha";//设置它显示的内容
self.textView.returnKeyType = UIReturnKeyDefault;//返回键的类型
self.textView.keyboardType = UIKeyboardTypeDefault;//键盘类型
textView.contentInset = UIEdgeInsetsMake(-11, -6, 0, 0); //添加滚动区域
self.textView.scrollEnabled = YES;//是否可以拖动
self.textView.editable = NO;//禁止编辑
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度
[textView becomeFirstResponder];//成为第一响应者
[textView resignFirstResponse]; //取消第一响应
[self.view addSubview: self.textView];//加入到整个页面中
2.设置textView的行间距
1.如果只是静态显示textView的内容为设置的行间距,执行如下代码:
// textview 改变字体的行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:@"输入你的内容" attributes:attributes];
2.如果是想在输入内容的时候就按照设置的行间距进行动态改变,那就需要将上面代码放到textView的delegate方法里
-(void)textViewDidChange:(UITextView *)textView
{
// textview 改变字体的行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 20;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}
3.设置textView的placeholder
UITextView上如何加上类似于UITextField的placeholder呢,其实在UITextView上加上一个UILabel或者UITextView,如果用UILable的话,会出现一个问题就是当placeholder的文字过长导致换行的时候就会出现问题,而用UITextView则可以有效避免此问题。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{ if (![text isEqualToString:@""])
{
_placeholderLabel.hidden = YES;
}
if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)
{
_placeholderLabel.hidden = NO;
}
return YES;
}
说明如下:
(1) _placeholderLabel 是加在UITextView后面的UITextView,_placeholderLabel要保证和真正的输入框的设置一样,字体设置成浅灰色,然后[_placeholderLabel setEditable:NO];真正的输入框要设置背景色透明,保证能看到底部的_placeholderLabel。
(2) [text isEqualToString:@""] 表示输入的是退格键
(3) range.location == 0 && range.length == 1 表示输入的是第一个字符