textview

作者: 赤焰军少帅林殊 | 来源:发表于2018-01-17 11:30 被阅读25次

    光标定位

        _textField.textContainerInset = UIEdgeInsetsMake(10*kRating, 11*kRating, 15*kRating, 15*kRating);
    
    #import "ZYTextView.h"
    
    @implementation ZYTextView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            
            self.placeholderColor = [UIColor lightGrayColor];
            
            self.placeholder = @"请输入内容";
            // 设置默认字体
            self.font = [UIFont systemFontOfSize:15];
            
        }
        return self;
    }
    
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect {
        // Drawing code
        NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
        attrs[NSFontAttributeName] = self.font;
        attrs[NSForegroundColorAttributeName] = self.placeholderColor;
        
        [self.placeholder drawInRect:CGRectMake(15*kRating, 10*kRating, self.frame.size.width, self.frame.size.height) withAttributes:attrs];
    }
    
    // 布局子控件的时候需要重绘
    - (void)layoutSubviews
    {
        [super layoutSubviews];
        [self setNeedsDisplay];
        
    }
    // 设置属性的时候需要重绘,所以需要重写相关属性的set方法
    - (void)setPlaceholder:(NSString *)placeholder
    {
        _placeholder = placeholder;
        [self setNeedsDisplay];
    }
    
    - (void)setPlaceholderColor:(UIColor *)placeholderColor
    {
        _placeholderColor = placeholderColor;
        [self setNeedsDisplay];
        
    }
    
    - (void)setFont:(UIFont *)font
    {
        [super setFont:font];
        [self setNeedsDisplay];
    }
    
    - (void)setText:(NSString *)text
    {
        [super setText:text];
        if (text.length) { // 因为是在文本改变的代理方法中判断是否显示placeholder,而通过代码设置text的方式又不会调用文本改变的代理方法,所以再此根据text是否不为空判断是否显示placeholder。
            self.placeholder = @"";
        }
        [self setNeedsDisplay];
    }
    
    - (void)setAttributedText:(NSAttributedString *)attributedText
    {
        [super setAttributedText:attributedText];
        if (attributedText.length) {
            self.placeholder = @"";
        }
        [self setNeedsDisplay];
    }
    
    

    相关文章

      网友评论

          本文标题:textview

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