0
我知道这里有很多关于UITextView占位符的链接,我尝试了为我工作的那个,但我不工作。即使当我开始在textView中输入时,他们的占位符文本仍然存在。任何人有任何想法,为什么?下面粘贴了我的代码。UITextView标签中的占位符不会消失
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
我不确定你的意思是什么? – 2012-03-21 22:52:12
您粘贴的代码在用户将文本输入到UITextView时不会工作。 ' - (void)textViewDidChange:(UITextView *)theTextView {...}'只有在选择另一个字段或隐藏键盘之后才会被调用。 'textViewDidBeginEditing:'将在用户开始输入时立即调用UITextView的。 – MechEthan 2012-03-21 23:25:22
这很有道理。我想通过另一种方式来做到这一点。我只是添加了一个观察者'UITextViewTextDidBeginEditingNotification',并且这个函数删除了占位符,一旦该通知被调用:) – 2012-03-21 23:34:16