textView使用小结

textView使用小结:(仿QQ空间留言输入)

效果图如下:

textView从中间慢慢往上输出

  这里主要使用的是textView的一个属性值:textContainerInset

  代码如下:

1
2
3
4
5
6
7

- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
_textView.textContainerInset = UIEdgeInsetsMake(CGRectGetHeight(_textView.frame) * 0.5 +8, 0, 0, 0);

}

    刚开始的时候设置textView的光标,也即是系统内部的UITextContainerView的偏移量为_textView的中间。
接着,我们在输入的过程中,需要将已经输入的文字网上移动,这里还是要改变UITextContainerView的偏移量就行了。操作属性textContainerInset,这里注意需要在textView的代理方法里实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#pragma mark -- UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
GBFillJobStateCell *cell = CELL_SUBVIEW_TABLEVIEW(textView, self.tableview);

// 设置textView默认显示的文字
if (textView.text.length == 0) {

cell.placeholdText.hidden = NO;
}else{

cell.placeholdText.hidden = YES;
}

CGSize tH = [self textSizeWithTextView:(UITextView *)textView Font:textView.font.pointSize text:nil];
CGFloat offset = (textView.frame.size.height - tH.height)/2.f;

// 设置textContainerInset属性
textView.textContainerInset = UIEdgeInsetsMake(offset, 0, offset, 0);

}

- (CGSize)textSizeWithTextView:(UITextView *)textView Font:(CGFloat)font text:(NSString *)string
{
NSString *text = string ? string : textView.text;

CGFloat tMargen = textView.textContainer.lineFragmentPadding * 2;
CGFloat tW = textView.frame.size.width - tMargen;
CGSize tSize = [text boundingRectWithSize:CGSizeMake(tW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;
return tSize;
}
坚持原创技术分享,您的支持将鼓励我继续创作!

热评文章

Fork me on GitHub