参考链接
废话不多说直接上代码
#define textFont [UIFont systemFontOfSize:16]
@interface ViewController ()<UITextViewDelegate>
@property (nonatomic) UITextView *textView;
@property (nonatomic, assign, getter=isMark) BOOL mark;
@end
创建textView,并设置属性
- (UITextView *)textView {
if (!_textView) {
_textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 300, 30)];
_textView.font = textFont;
//文本内容必须要设置,不然行间距的设置不起作用,这里以输入一个空格为例
_textView.text = @" ";
//设置整个控件文字的上下距离
_textView.textContainerInset = UIEdgeInsetsMake(5, 0, 5, 0);
//NSMutableParagraphStyle 设置段落风格
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//设置段落的行间距
paragraphStyle.lineSpacing = 5;
NSDictionary *attributes = @{
NSFontAttributeName:textFont,
NSParagraphStyleAttributeName:paragraphStyle};
//NSAttributedString 富文本用来设置文字的样式
_textView.attributedText = [[NSAttributedString alloc] initWithString:_textView.text attributes:attributes];
_textView.delegate = self;
_textView.backgroundColor = [UIColor grayColor];
[self.view addSubview:_textView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotification object:_textView];
}
return _textView;
}
通知事件
/**
* 设置输入超过三行(高度78,高度计算所得,字体大小的和+行间距的和)自动滚入不可见区域
*/
- (void)textViewTextDidChange:(NSNotification *)notification {
//hasPrefix:方法的功能是判断创建的字符串内容是否以某个字符开始
if ([self.textView.text hasPrefix:@" "]) {
self.textView.text = [self.textView.text stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
CGFloat height =self.textView.contentSize.height > 78 ? 78 : self.textView.contentSize.height;
self.textView.frame = CGRectMake(50, CGRectGetMaxY(self.textView.frame) - height, self.textView.frame.size.width, height);
return;
}
代理方法
#pragma mark - UITextViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
_mark = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
_mark = NO;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//判断是否拖动来设置frame
if (!self.isMark) {
NSLog(@"%lf", self.textView.contentSize.height);
if (self.textView.contentSize.height > 78) {
[self.textView setContentOffset:CGPointMake(0, self.textView.contentSize.height - 78)];
} else {
[self.textView setContentOffset:CGPointMake(0, 0)];
}
}
}
网友评论