UITextView - 2

来源:互联网 发布:网络推广挣钱 编辑:程序博客网 时间:2024/06/04 00:22

上面一篇讲述了UITextView的简单使用,但是我们在微信等社交APP经常会见到UITextView的一些使用是这样的:

  

随着输入的字数,行数不断增加,并达到一定的高度后不再增加,用户可以用滚动条查看全部text。

这个其实就是UITextView对高度的自适应。要解决这个问题,首先我们必须对几个重要的属性的彻底理解才能达到游刃而解的效果。


因为UITextView是继承UIScrollView的,而对于内容展示而言,UIScrollView下面几个属性非常地重要:

@property(nonatomic)         CGPoint                      contentOffset;                  // default CGPointZero@property(nonatomic)         CGSize                       contentSize;                    // default CGSizeZero@property(nonatomic)         UIEdgeInsets                 contentInset;                   // default UIEdgeInsetsZero. add additional scroll area around content

我之前的文章学习是有专门对这几个属性的学习的,可以参考大神的博客:

http://www.cnblogs.com/kenshincui/p/3913885.html#UIScrollView

理解好这张图片就足矣:


参考好上面这个文章,我这里给出一个简单的例子:

#import "LBTextViewNewController.h"@interface LBTextViewNewController () <UITextViewDelegate>@property (nonatomic, strong) UITextView* myTextView;@end@implementation LBTextViewNewController- (void)viewDidLoad{    [super viewDidLoad];        self.myTextView = [[UITextView alloc] init];    [self.myTextView setFrame:CGRectMake(0, 0, 300, 150)];    [self.myTextView setCenter:CGPointMake(self.view.center.x, self.view.center.y - 50)];    [self.myTextView setDelegate:self];    [self.myTextView setReturnKeyType:UIReturnKeyNext];    [self.myTextView setScrollEnabled:YES];    [self.myTextView setFont:[UIFont systemFontOfSize:18.0]];    [self.myTextView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];        [self.myTextView.layer setBackgroundColor:[UIColor clearColor].CGColor];    [self.myTextView.layer setBorderColor:[UIColor lightGrayColor].CGColor];    [self.myTextView.layer setBorderWidth:1.0];    [self.myTextView.layer setCornerRadius:8.0f];    [self.myTextView.layer setMasksToBounds:YES];        [self.myTextView setText:@"守夜人誓言:“长夜将至,我从今开始守望,至死方休。我将不娶妻、不封地、不生子。我将不戴宝冠,不争荣宠。我将尽忠职守,生死於斯。我是黑暗中的利剑,长城上的守卫。我是抵御寒冷的烈焰,破晓时分的光线,唤醒眠者的号角,守护王国的坚盾。我将生命与荣耀献给守夜人,今夜如此,夜夜皆然。守夜人誓言:“长夜将至,我从今开始守望,至死方休。我将不娶妻、不封地、不生子。我将不戴宝冠,不争荣宠。我将尽忠职守,生死於斯。我是黑暗中的利剑,长城上的守卫。我是抵御寒冷的烈焰,破晓时分的光线,唤醒眠者的号角,守护王国的坚盾。我将生命与荣耀献给守夜人,今夜如此,夜夜皆然。"];        [self.view addSubview:self.myTextView];        NSLog(@"self.myTextView.contentOffset: %@", NSStringFromCGPoint(self.myTextView.contentOffset));    NSLog(@"self.myTextView.contentInset: %@", NSStringFromUIEdgeInsets(self.myTextView.contentInset));        [self performSelector:@selector(adjusetTextViewContentOffset) withObject:nil afterDelay:3.0];    }- (void)adjusetTextViewContentOffset{    [self.myTextView setContentOffset:CGPointMake(0, 150) animated:YES];}@end

可以看到延迟3秒后内容会自动上移动,试着将:

[self.myTextView setContentOffset:CGPointMake(0, 150) animated:YES];

150改成-150,会发现上面多了一条空白空间,明白了这个巧妙的特性之后,相信对自适应就有很好的解决方法了吧:

当一定高度之内,输入框可以随着输入内容的高度增加而自动增加,而达到一定的高度后(例如一定行数),输入框的高度不再调整,而使得内容的偏离度改变只展示后面的text内容。


但说得容易,实际做起来的确不容易,下面的篇章会仔细讲解(甚至会讲解多种方法)。


1 0