首页 > 代码库 > UITextView仿微信输入
UITextView仿微信输入
UITextView仿微信输入
输入和删除文字的时候不会出现抖动,也不会出现一行文字显示一半的情况,代码中部分数据用的是死数据,用的时候要灵活运用,适当调整一下!
#define textFont [UIFont systemFontOfSize:16]
#import "ViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (nonatomic, weak) UITextView *textView;
@property (nonatomic, assign, getter=isMark) BOOL mark;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(100, 200, 214, 30)];
_textView=textView;
_textView.font=textFont;
//不然设置的行间距不起作用
_textView.text=@" ";
//设置控件文字的上下距离
_textView.textContainerInset=UIEdgeInsetsMake(5, 0, 5, 0);
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:textFont,
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
_textView.delegate=self;
textView.backgroundColor=[UIColor redColor];
[self.view addSubview:textView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotification object:textView];
}
/**
* 设置输入超过三行(高度78)自动滚入不可见区域
*
* @param notification <#notification description#>
*/
- (void)textViewTextDidChange:(NSNotification *)notification{
if([_textView.text hasPrefix:@" "]){
_textView.text=[_textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}
CGFloat height = _textView.contentSize.height>78?78:_textView.contentSize.height;
_textView.frame=CGRectMake(100, CGRectGetMaxY(_textView.frame)-height, _textView.frame.size.width, height);
return;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
_mark=YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
_mark=NO;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
/**
* 判断是否拖动来设置frame
*/
if(!self.isMark){
NSLog(@"%lf",_textView.contentSize.height);
if(_textView.contentSize.height>78){
[_textView setContentOffset:CGPointMake(0, _textView.contentSize.height-78)];
}else{
[_textView setContentOffset:CGPointMake(0, 0)];
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
UITextView仿微信输入