UITextView高度随文字自动增加

这里写图片描述
这里写图片描述
代码如下:

#define DEVICE_HEIGHT [UIScreen mainScreen].bounds.size.height
#import "ViewController.h"

@interface ViewController ()<UITextViewDelegate>
@property (nonatomic, strong) UITextView *textView;
// 是否有滚动
@property (nonatomic, assign, getter=scrollFlag) BOOL flag;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.title = @"UITextView高度随文字自动增加";
    [self setupUI];
}

-(void)setupUI{
    // UITextView
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(100, (64+150), (UIScreen.mainScreen.bounds.size.width - 200), 30)];
    self.textView.font = [UIFont systemFontOfSize:17.0f];
    self.textView.delegate = self;
    self.textView.layer.masksToBounds = YES;
    self.textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView.layer.borderWidth = 0.5;
    // 调整光标的位置,让光标出现在UITextView的正中间
    self.textView.textContainerInset = UIEdgeInsetsMake(5, 0, 0, 0);
    [self.view addSubview:self.textView];

    // 改变文字的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:self.textView];
}


- (void)textViewDidChange:(NSNotification*)notification{
    if ([_textView.text hasPrefix:@""]){
        self.textView.text = [_textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    CGFloat height = _textView.contentSize.height > 70? 70:_textView.contentSize.height + 5;
    [UIView animateWithDuration:0.3 animations:^{
        self.textView.frame = CGRectMake(100, CGRectGetMaxY(self.textView.frame)-height, self.textView.frame.size.width, height);
    }];
    return;
}

// 可以滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.flag = YES;
}

// 不可以滚动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.flag = NO;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"%@",NSStringFromCGPoint(self.textView.contentOffset));
//    // 判断是否拖动来设置frame,这样可以使frame的变化不那么突然,平稳过度
    if (!self.scrollFlag){
        NSLog(@"%lf",_textView.contentSize.height);
        if (_textView.contentSize.height > 70){
            [_textView setContentOffset:CGPointMake(0, _textView.contentSize.height - 70 + 5)];
        }else{
            [_textView setContentOffset:CGPointMake(0, 0)];

        }
    }
}

猜你喜欢

转载自blog.csdn.net/u012581760/article/details/81095058