美文网首页
iOS使用重绘(drawRect)在textView中添加 pl

iOS使用重绘(drawRect)在textView中添加 pl

作者: 闻人歌 | 来源:发表于2018-10-15 11:30 被阅读9次

我们在使用用户输入控件的时候,经常会用到placeHolder(占位符),textField 控件自带了占位符.但是 textView 却没有自带占位符属性.那如果要在 textView 使用的时候添加一个占位文字并展示

一般的做法,是在 textView 上添加一个亮灰色的 label,然后监听 textView 是否输入,有内容输入的时候移除 place_holder_label

现在我们使用重绘的方法,模拟 textField 实现占位文字的效果.drawRect介绍

  • 创建一个 CustomTextView 类继承自 UITextView,在其中添加 placeHolder, placeHolderColor 属性
@interface CustomTextView : UITextView

@property (nonatomic, copy)NSString  *placeHolder;
@property (nonatomic, strong)UIColor *placeHolderColor;

@end
  • 实现重绘方法,在确定有占位文字时,将 placeHolder 重绘
- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    if (self.text.length==0 && self.placeHolder) {
        CGRect rect1 = CGRectMake(10.f, 7.0f, rect.size.width, rect.size.height); 
        [self.placeHolderColor set];
        if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_0) {
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
            paragraphStyle.alignment = self.textAlignment;
            
            [self.placeHolder drawInRect:rect1
                          withAttributes:@{ NSFontAttributeName : self.font,
                                            NSForegroundColorAttributeName : self.placeHolderColor,
                                            NSParagraphStyleAttributeName : paragraphStyle }];
        }else{
            [self.placeHolder drawInRect:rect1
                                withFont:self.font
                           lineBreakMode:NSLineBreakByTruncatingTail
                               alignment:self.textAlignment];
        }
    }
    
}
  • 在不同的场景下,对 place_holder_label 进行重绘
- (void)_setup{
    
    _placeHolderColor = [UIColor lightGrayColor];
    self.textColor = [UIColor blackColor];
    self.font = [UIFont systemFontOfSize:16.f];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentChanged:) name:UITextViewTextDidChangeNotification object:self];
}

- (void)contentChanged:(NSNotification *)noti{
    [self setNeedsDisplay];
}
- (void)setText:(NSString *)text{
    [super setText:text];
    [self setNeedsDisplay];
}

- (void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}

- (void)setPlaceHolder:(NSString *)placeHolder{
    if ([_placeHolder isEqualToString:placeHolder]) {
        return;
    }
    
    _placeHolder = placeHolder;
    [self setNeedsDisplay];
}

- (void)setPlaceHolderColor:(UIColor *)placeHolderColor{
    if (_placeHolderColor == placeHolderColor) {
        return;
    }
    _placeHolderColor = placeHolderColor;
    [self setNeedsDisplay];
}

相关文章

网友评论

      本文标题:iOS使用重绘(drawRect)在textView中添加 pl

      本文链接:https://www.haomeiwen.com/subject/zctfzftx.html