如何写好一个TextView使其文字不抖动

参考链接
废话不多说直接上代码

#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)];
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值