美文网首页
iOS textView添加占位符

iOS textView添加占位符

作者: coderJerry01 | 来源:发表于2017-10-26 14:12 被阅读126次

    其实需求很简单,想必你也会!但是万一有需要的同学呢!废话少说,看需求效果图:


    WechatIMG2983.jpeg WechatIMG2986.jpeg WechatIMG2991.jpeg

    textView正常情况下是没有占位符的,但是我们可以通过继承与textview 用他的drawRect方法绘制,代码如下:
    .h文件中添加属性

    @interface DXFeedBackTextView : UITextView
    /** 占位文字 /
    @property(nonatomic, copy) NSString placeholder;
    /
    占位文字颜色 */
    @property(nonatomic, strong) UIColor *placeholderColor;
    @end
    .m文件中实现代码如:
    @implementation DXFeedBackTextView

      - (instancetype)init{
    
    
       if (self = [super init]) {
        // 设置默认字
        self.font = [UIFont systemFontOfSize:17];
        // 设置默认颜色
        self.placeholderColor = [UIColor grayColor];
        // 使用通知监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    
    }
       return self;
    
    }
    
    - (void)textDidChange:(NSNotification *)note{
    
    // 会重新调用drawRect:方法
      [self setNeedsDisplay];
    
    }
    
    - (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
      /**
     * 每次调用drawRect:方法,都会将以前画的东西清除掉
     */
      - (void)drawRect:(CGRect)rect{
    // 如果有文字,就直接返回,不需要画占位文字
    if (self.hasText) return;
    // 属性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    // 画文字
    rect.origin.x = 5;
    rect.origin.y = 8;
    rect.size.width -= 2 * rect.origin.x;
    [self.placeholder drawInRect:rect withAttributes:attrs];
    }
    
    - (void)layoutSubviews{
      [super layoutSubviews];
      [self setNeedsDisplay];
    }
    
    #pragma mark - setter
    //重写setter方法调用setNeedsDisplay方法刷新
      - (void)setPlaceholder:(NSString *)placeholder{
        _placeholder = [placeholder copy];
        [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];
      [self setNeedsDisplay];
      }
    
    - (void)setAttributedText:(NSAttributedString *)attributedText{
        [super setAttributedText:attributedText];
        [self setNeedsDisplay];
    }
    

    @end

    打完收工!

    相关文章

      网友评论

          本文标题:iOS textView添加占位符

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