美文网首页iOS开发iOS学习开发
自定义具有占位文字的TextView

自定义具有占位文字的TextView

作者: 无意惹东风 | 来源:发表于2016-10-18 10:59 被阅读43次

    在UI控件中,经常会用到UITextField和UITextView,但是我们都知道对于UITextView而言,它本身是没有占位文字placeholder这一属性的,那么,本文就将介绍如何编写一个带有占位文字的TextView。

    1、首先自定义一个基于UITextView的YJPlaceholderTextView,.h文件中内容如下:

    @interface YJPlaceholderTextView : UITextView
    
    @property (copy ,nonatomic) NSString *placeholder;
    @property (strong ,nonatomic) UIColor *placeholderColor;
    
    @end
    

    2、然后在相应的.m文件中,我们做如下操作:

    #import "YJPlaceholderTextView.h"
    
    #define YJNotificationCenter [NSNotificationCenter defaultCenter]
    
    @implementation YJPlaceholderTextView
    
    - (id)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
    
            // 设置通知监听文字的改变
            [YJNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
        }
        return self;
    }
    

    在这里,我定义了一个通知类的宏,用来简便书写通知事件。
    然后,我们开始书写TextView:

    - (void)setPlaceholder:(NSString *)placeholder
    {
        _placeholder = [placeholder copy];
        [self setNeedsDisplay];
    }
    
    - (void)setPlaceholderColor:(UIColor *)placeholderColor
    {
        _placeholderColor = placeholderColor;
        [self setNeedsDisplay];
    }
    
    - (void)setText:(NSString *)text
    {
        [super setText:text];
        [self setNeedsDisplay];
    }
    
    -(void)setFont:(UIFont *)font
    {
        [super setFont:font];
        [self setNeedsDisplay];
    }
    

    显然,上面的这些方法是我们对自定义的textView的属性进行的重写,这里重写一系列方法只是为了在系统通过代码修改这些属性的时候能够一样发生反应。
    并且、在这里我们用到了“setNeedsDisplay”这个方法,他并不是会立刻执行的一个方法,只有在下一个消息循环时候才会发生调用。

    // 通知事件的响应方法
    - (void)textDidChange
    {
        // 重绘drawRect
        [self setNeedsDisplay];
    }
    

    最后,我们通过对“- (void)drawRect:(CGRect)rect”方法的调用来实现placeholder的相关设置。

    // 画占位文字
    - (void)drawRect:(CGRect)rect
    {
        if (self.hasText) return;
        
        CGFloat x = 5;
        CGFloat w = rect.size.width - 2*x;
        CGFloat y = 8;
        CGFloat h = rect.size.height - 2*y;
        CGRect placeholderRect = CGRectMake(x, y, w, h);
        NSMutableDictionary *attr = [NSMutableDictionary dictionary];
        attr[NSFontAttributeName] = self.font;
        // 在没有设置字体颜色时默认为灰色
        attr[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
        // 画占位文字
        [self.placeholder drawInRect:placeholderRect withAttributes:attr];
        
    }
    

    到此,我们的自定义含有placeholder的UITextView就写好了。

    希望我的文章能对大家有所帮助。康撒米哒~~~

    相关文章

      网友评论

        本文标题:自定义具有占位文字的TextView

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