Skip to content

Instantly share code, notes, and snippets.

@gonghao
Created March 6, 2014 08:38
Show Gist options
  • Save gonghao/9384988 to your computer and use it in GitHub Desktop.
Save gonghao/9384988 to your computer and use it in GitHub Desktop.
//
// UITextView+Placeholder.h
// DongXi
//
// Created by Gong Hao on 3/6/14.
// Copyright (c) 2014 Douban Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITextView (Placeholder) <UITextViewDelegate>
@property (nonatomic, strong) NSString *placeholderText;
@property (nonatomic, strong) UIColor *placeholderColor;
@end
//
// UITextView+Placeholder.m
// DongXi
//
// Created by Gong Hao on 3/6/14.
// Copyright (c) 2014 Douban Inc. All rights reserved.
//
#import <objc/runtime.h>
#import "UITextView+Placeholder.h"
static char const * const kKeyPlaceholderText = "Key+placeholderText";
static char const * const kKeyPlaceholderColor = "Key+placeholderColor";
static char const * const kKeyPalceholderView = "Key+placeholderView";
@implementation UITextField (Placeholder)
@dynamic placeholderText;
@dynamic placeholderColor;
- (NSString *)placeholderText
{
return objc_getAssociatedObject(self, kKeyPlaceholderText);
}
- (void)setPlaceholderText:(NSString *)placeholderText
{
objc_setAssociatedObject(self, kKeyPlaceholderText, placeholderText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.delegate = self;
[self updatePlaceholder];
}
- (UIColor *)placeholderColor
{
return objc_getAssociatedObject(self, kKeyPlaceholderColor);
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
objc_setAssociatedObject(self, kKeyPlaceholderColor, placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updatePlaceholder];
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
[self togglePlaceholder:NO];
[self becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
[self togglePlaceholder:YES];
}
[self resignFirstResponder];
}
- (void)updatePlaceholder
{
UILabel *placeholderView = objc_getAssociatedObject(self, kKeyPalceholderView);
if (!placeholderView) {
placeholderView = [[UILabel alloc] initWithFrame:CGRectMake(4, 4, self.frame.size.width, self.font.lineHeight)];
[self addSubview:placeholderView];
objc_setAssociatedObject(self, kKeyPalceholderView, placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
placeholderView.font = self.font;
placeholderView.textColor = self.placeholderColor ? self.placeholderColor : [UIColor lightGrayColor];
if (self.placeholderText) {
placeholderView.text = self.placeholderText;
placeholderView.hidden = NO;
} else {
placeholderView.hidden = YES;
}
}
- (void)togglePlaceholder:(BOOL)on
{
UILabel *placeholderView = objc_getAssociatedObject(self, kKeyPalceholderView);
if (placeholderView) {
placeholderView.hidden = !on;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment