UITextView标签中的占位符不会消失

时间:2012-03-21 21:44:56

标签: objective-c xcode4.2 uitextview contentplaceholder

我知道这里有很多链接用于UITextView的占位符,我尝试了一个适合我的,但我不工作。即使我开始在textView中输入,他们的占位符文本仍然存在。任何人有任何想法为什么?我在下面粘贴了我的代码。

AddExerciseViewController.m

 #import "AddExerciseViewController.h"

 @implementation AddExerciseViewController
 @synthesize nameTextField = _nameTextField;
 @synthesize descriptionTextView = _descriptionTextView;
 @synthesize placeholderLabel = _placeholderLabel;

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {     
     }
     return self;
 }

 - (void)viewDidLoad
 {
     _descriptionTextView.layer.borderWidth = 3.0f;
     _descriptionTextView.layer.borderColor = [[UIColor grayColor ] CGColor];
     _descriptionTextView.layer.cornerRadius = 5;
     _descriptionTextView.clipsToBounds = YES;

    _placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,           _descriptionTextView.frame.size.width - 20.0, 34.0)];
     [_placeholderLabel setText: @"FooBar"];

     // placeholderLabel is instance variable retained by view controller
     [_placeholderLabel setBackgroundColor:[UIColor clearColor]];
     [_placeholderLabel setTextColor:[UIColor lightGrayColor]];

     [_descriptionTextView addSubview:_placeholderLabel];
     [super viewDidLoad];
 }

 - (void) textViewDidChange:(UITextView *)theTextView
 {
     if(![_descriptionTextView hasText]) {
    [_descriptionTextView addSubview:_placeholderLabel];
    [UIView animateWithDuration:0.15 animations:^{
        _descriptionTextView.alpha = 1.0;
    }];
 } else if ([[_descriptionTextView subviews] containsObject:_placeholderLabel]) {

    [UIView animateWithDuration:0.15 animations:^{
        _placeholderLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [_placeholderLabel removeFromSuperview];
    }];
}
 }


 - (void)textViewDidEndEditing:(UITextView *)theTextView
 {
     if (![_descriptionTextView hasText]) {
         [_descriptionTextView addSubview:_placeholderLabel];
         [UIView animateWithDuration:0.15 animations:^{
             _placeholderLabel.alpha = 1.0;
         }];
     }
 }

 - (void)viewDidUnload
 {
     [self setDescriptionTextView:nil];
     [self setNameTextField:nil];
     [super viewDidUnload];
 }

@end

1 个答案:

答案 0 :(得分:0)

我相信只有在编辑完成后才会调用textViewDidChange:。您可能希望隐藏textViewDidBeginEditing:上的占位符。