有placeholder的UITextView

2016-06-04  本文已影响50人  低吟浅唱1990

<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

-(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>

上一篇 下一篇

猜你喜欢

热点阅读