美文网首页
有placeholder的UITextView

有placeholder的UITextView

作者: 低吟浅唱1990 | 来源:发表于2016-06-04 09:47 被阅读50次

    <pre>

    import <UIKit/UIKit.h>

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

    @end

    import "PlaceholderTextView.h"

    @interface PlaceholderTextView ()

    @property(nonatomic, strong)UILabel *placeLable;

    @end

    @implementation PlaceholderTextView

    • (instancetype)initWithFrame:(CGRect)frame
      {
      self = [super initWithFrame:frame];
      if (self) {

        self.backgroundColor = [UIColor clearColor];
        UILabel *placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30)];
        placeLabel.numberOfLines = 0;
        placeLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:placeLabel];
        
        self.placeLable = placeLabel;
        self.font = [UIFont systemFontOfSize:16.0];
        self.placeholderColor = [UIColor grayColor];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextViewTextDidChangeNotification object:self];
      

      }
      return self;
      }

    -(void)setPlaceholder:(NSString *)placeholder{

    _placeholder = [placeholder copy];
    self.placeLable.text = _placeholder;
    [self setNeedsLayout];
    

    }

    -(void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor;
    self.placeLable.textColor = _placeholderColor;
    }

    -(void)layoutSubviews{

    [super layoutSubviews];
    
    CGRect temp = _placeLable.frame;
    temp.origin.y = 8.0f;
    temp.origin.x = 5.0f;
    temp.size.width = self.frame.size.width - 2*temp.origin.x;
    CGSize size = [self.placeLable sizeThatFits:CGSizeMake(temp.size.width, MAXFLOAT)];
    self.placeLable.frame = CGRectMake(5, 8, temp.size.width,size.height);
    

    }
    -(void)setFont:(UIFont *)font{

    [super setFont:font];
    self.placeLable.font = font;
    
    [self setNeedsLayout];
    

    }

    -(void)setText:(NSString *)text{

    [super setText:text];
    [self textChanged];
    

    }

    -(void)textChanged{

    if (self.text.length == 0) {
        self.placeLable.hidden = NO;
    }else{
        self.placeLable.hidden = YES;
    }
    

    }

    -(void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    

    }

    @end

    </pre>

    相关文章

      网友评论

          本文标题:有placeholder的UITextView

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