Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created March 6, 2013 15:23
Show Gist options
  • Save rajivnarayana/5100049 to your computer and use it in GitHub Desktop.
Save rajivnarayana/5100049 to your computer and use it in GitHub Desktop.
Custom UITextView with a placeholder label.
//
// MyTextView.m
// TextViewDemo
//
// Created by Jayaprada on 10/11/12.
// Copyright (c) 2012 mountain lion. All rights reserved.
//
#import "MyTextView.h"
@interface MyTextView () {
UILabel *placeHolderLabel;
}
@property(nonatomic, strong) NSString *placeHolder;
@end
@implementation MyTextView
@synthesize placeHolder;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self customInit];
}
return self;
}
- (void) customInit {
placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
placeHolderLabel.font = self.font;
placeHolderLabel.frame = CGRectMake(10, 7, self.bounds.size.width-10, 22.f);
// placeHolderLabel.frame = self.inputView.frame;
// placeHolderLabel.autoresizingMask = self.inputView.autoresizingMask;
placeHolderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
placeHolderLabel.textColor = [UIColor lightGrayColor];
placeHolderLabel.backgroundColor = [UIColor clearColor];
[self addSubview:placeHolderLabel];
[self sendSubviewToBack:placeHolderLabel];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:self];
}
- (void) textChanged:(id) sender {
placeHolderLabel.hidden = self.text.length > 0;
}
- (id) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (void) setText:(NSString *)text {
[super setText:text];
}
- (void) setPlaceHolder:(NSString *)placeHolder1 {
placeHolder = placeHolder1;
placeHolderLabel.text = placeHolder;
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment