@interface SSTextView : UITextView {
BOOL _shouldDrawPlaceholder;
}
/**
The string that is displayed when there is no other text in the text view.
The default value is `nil`.
*/
@property (nonatomic) NSString *placeholder;
/**
The color of the placeholder.
The default is `[UIColor lightGrayColor]`.
*/
@property (nonatomic) UIColor *placeholderColor;
@end
#import "SSTextView.h"
@interfaceSSTextView ()
- (void)_initialize;
- (void)_updateShouldDrawPlaceholder;
- (void)_textChanged:(NSNotification *)notification;
@end
@implementation SSTextView
#pragma mark - Accessors
@synthesize placeholder = _placeholder;
@synthesize placeholderColor = _placeholderColor;
- (void)setText:(NSString *)string {
[super setText:string];
[self_updateShouldDrawPlaceholder];
}
- (void)setPlaceholder:(NSString *)string {
if ([string isEqual:_placeholder]) {
return;
}
_placeholder = string;
[self_updateShouldDrawPlaceholder];
}
#pragma mark - NSObject
- (void)dealloc {
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:UITextViewTextDidChangeNotificationobject:self];
}
#pragma mark - UIView
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self _initialize];
}
returnself;
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self _initialize];
}
returnself;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
if (_shouldDrawPlaceholder) {
[_placeholderColorset];
[_placeholderdrawInRect:CGRectMake(8.0f, 5.0f, self.frame.size.width - 16.0f, self.frame.size.height - 16.0f) withAttributes:[NSDictionarydictionaryWithObject:self.placeholderColorforKey:NSForegroundColorAttributeName]];
}
}
}
#pragma mark - Private
- (void)_initialize {
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(_textChanged:) name:UITextViewTextDidChangeNotificationobject:self];
self.placeholderColor = [UIColorcolorWithWhite:0.702falpha:1.0f];
_shouldDrawPlaceholder = NO;
}
- (void)_updateShouldDrawPlaceholder {
BOOL prev = _shouldDrawPlaceholder;
_shouldDrawPlaceholder = self.placeholder && self.placeholderColor && self.text.length == 0;
if (prev != _shouldDrawPlaceholder) {
[selfsetNeedsDisplay];
}
}
- (void)_textChanged:(NSNotification *)notificaiton {
[self_updateShouldDrawPlaceholder];
}
@end