UITextView

简介

  • UITextView 具有 label 大部分属性,以及 textField 的属性。

1、UITextView 的创建与设置

UITextView *textView = [[UITextView alloc] init];
// 将 textView 添加到 view
[self addSubview:textView];
// 设置位置尺寸
textView.frame = CGRectMake(10, 30, self.width, 400);
// 设置背景颜色
textView.backgroundColor = [UIColor lightGrayColor];
// 设置文本:由于 UITextView 具有滚动功能,当 text 文本内容较多时可以实现滚动阅读和编辑
textView.text = @"写代码快乐\n15911110524\n写代码快乐\nhttps://www.baidu.com\n写代码快乐";
// 设置对齐方式
textView.textAlignment = NSTextAlignmentLeft;
// 设置文本颜色
textView.textColor = [UIColor redColor];
// 设置字体
textView.font = [UIFont boldSystemFontOfSize:20];
// 对文本中的电话和网址自动加链接
textView.dataDetectorTypes = UIDataDetectorTypeAll;
// 禁止编辑:设置为只读,不再能输入内容
textView.editable = NO;
// 禁止选择:禁止选中文本,此时文本也禁止编辑
textView.selectable = NO;
// 禁止滚动
textView.scrollEnabled = NO;
// 获取当前选择的范围
NSRange range = textView.selectedRange;
// 设置可以对选中的文字加粗:选中文字时可以对选中的文字加粗
textView.allowsEditingTextAttributes = YES;
// 设置 textView 的代理,需遵守协议 <UITextViewDelegate>
textView.delegate = self;

2、UITextViewDelegate 的协议方法

  • 需遵守协议 UITextViewDelegate,并设置代理
// 将要开始编辑,编辑开始前被调用
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
	return YES;
}

// 已经开始编辑,编辑开始后被调用
- (void)textViewDidBeginEditing:(UITextView *)textView {

}

// 将要结束编辑,编辑结束前被调用
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
	return YES;
}

// 已经结束编辑,编辑结束后被调用
- (void)textViewDidEndEditing:(UITextView *)textView {
	NSLog(@"编辑的内容是 : %@", textView.text);
}

// 文本修改,文本修改前被调用
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
	return YES;
}

// 文本变更,文本变更时被调用,每输入一个字符时都会被调用
- (void)textViewDidChange:(UITextView *)textView {

}

// 游标移动,选择范围发生变化时被调用
- (void)textViewDidChangeSelection:(UITextView *)textView {

}
  • UITextView富文本
posted @ 2018-11-12 23:00  CH520  阅读(376)  评论(0编辑  收藏  举报