首页 > 代码库 > iOS中用UILabel实现UITextView的占位文字

iOS中用UILabel实现UITextView的占位文字

 

@interface BSPublishTextView : UITextView

/** 对外属性占位字符 placeholder */

@property (nonatomic, copy) NSString *placeholder;

 

/** 对外属性占位符颜色 */

@property (nonatomic, strong) UIColor *placeholderColor;

@end

@interface BSPublishTextView ()

/** 占位字符 label */

@property (nonatomic, weak) UILabel *placeholderLabel;

@end

 

@implementation BSPublishTextView

- (UILabel *)placeholderLabel{

    if (!_placeholderLabel) {

        UILabel *placeholderLabel = [[UILabel alloc]init];

        placeholderLabel.backgroundColor = [UIColor greenColor];

        placeholderLabel.numberOfLines = 0;

        placeholderLabel.x = 4;

        placeholderLabel.y = 7;

        [self addSubview:placeholderLabel];

        _placeholderLabel = placeholderLabel;

    }

    return _placeholderLabel;

}

 

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // 永久垂直有弹簧效果

        self.alwaysBounceVertical = YES;

        self.font = [UIFont systemFontOfSize:15];

        self.placeholderColor = [UIColor grayColor];

     

        // 注册通知 当收到 UITextViewTextDidChangeNotification  textView文字改变时

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];    

    }

    return self;

}

 

//通知调用方法

- (void)textChange{

    self.placeholderLabel.hidden = self.hasText;

}

 

- (void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}

 

- (void)layoutSubviews{

    [super layoutSubviews];

    //在 layoutSubviews 拿到 UITextView的宽度一定是正确的 ,这里如果外界即使更改了UITextView的宽度这里也是能算正确的

    //先设置placeholderLabel占位字符的宽度

     self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x;

 

    // placeholderLabel占位字符的大小size随里面的内容大小而变化

    [self.placeholderLabel sizeToFit];

}

 

// setNeedsDisplay方法 : 会在恰当的时刻自动调用drawRect:方法

// setNeedsLayout方法 : 会在恰当的时刻调用layoutSubviews方法

 

- (void)setPlaceholderColor:(UIColor *)placeholderColor{

    _placeholderColor = placeholderColor;

    self.placeholderLabel.textColor = placeholderColor;

}

 

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

    _placeholder = [placeholder copy];

    self.placeholderLabel.text = placeholder;

    [self setNeedsLayout]; //会在恰当的时刻调用layoutSubviews方法 这句代码可不写

}

 

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

    [super setFont:font];

    self.placeholderLabel.font = font;

    [self setNeedsLayout];  //会在恰当的时刻调用layoutSubviews方法 这句代码可不写

}

 

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

    [super setText:text];

    [self textChange];

}

 

- (void)setAttributedText:(NSAttributedString *)attributedText{

    [super setAttributedText:attributedText];

    [self textChange];

}

@end

 

iOS中用UILabel实现UITextView的占位文字