iphone自定义UITextView的placeholder

长平狐 发布于 2013/12/25 17:17
阅读 258
收藏 0

大家都知道UITextField才有placeholder属性,UITextView 并没有placeholder,那么怎么模拟UITextfield使UITextView也有placeholder。

思路是:继承uitextview,判断当text为空时就让[super text]显示placeholder。

代码如下(我引用了arc):

UIPlaceholderTextView.h

#import <UIKit/UIKit.h>

@interface UIPlaceholderTextView : UITextView
@property(nonatomic, strong) NSString *placeholder;     //占位符

-(void)addObserver;//添加通知
-(void)removeobserver;//移除通知
@end

UIPlaceholderTextView.m

#import "UIPlaceholderTextView.h"

@interface UIPlaceholderTextView ()

@property (nonatomic, strong) UIColor* textColor;

- (void) beginEditing:(NSNotification*) notification;
- (void) endEditing:(NSNotification*) notification;

@end

@implementation UIPlaceholderTextView
@synthesize placeholder;
@synthesize textColor;
- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self awakeFromNib];
    }
    return self;
}
//当用nib创建时会调用此方法
- (void)awakeFromNib {
    textColor = [UIColor redColor];
    [self addObserver];
}
-(void)addObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditing:) name:UITextViewTextDidEndEditingNotification object:self];
}
-(void)removeobserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark Setter/Getters
- (void) setPlaceholder:(NSString *)aPlaceholder {
    placeholder = aPlaceholder;
    [self endEditing:nil];
}

- (NSString *) text {
    NSString* text = [super text];
    if ([text isEqualToString:placeholder]) return @"";
    return text;
}

- (void) beginEditing:(NSNotification*) notification {
    if ([super.text isEqualToString:placeholder]) {
        super.text = nil;
        //字体颜色
        [super setTextColor:textColor];
    }
    
}

- (void) endEditing:(NSNotification*) notification {
    if ([super.text isEqualToString:@""] || self.text == nil) {
        super.text = placeholder;
        //注释颜色
        [super setTextColor:[UIColor lightGrayColor]];
    }
}

在ViewController中用时,1、在xib上加一个uitextview连接上,2、直接创建initframe

但是不要忘了,placeholder,和添加通知,移除通知。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.textView.placeholder = @"请添写你的信息……";
    
	// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.textView addObserver];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [self.textView removeobserver];
}

微笑


效果图:

     


欢迎大家,有更好的方法提出!



原文链接:http://blog.csdn.net/rhljiayou/article/details/9340657
加载中
返回顶部
顶部