我想在我的UITextView中有一个占位符,我宁愿避免像拖出方法(重载代码)和子类化这样的复杂性。我只需要保留编辑。
我目前正在使用此方法在UITextView
·H
@property (weak, nonatomic) IBOutlet UITextView *gcTextView;
的.m
@synthesize gcTextView;
将此添加到viewDidLoad:
self.gcTextView.text = @"placeholder text here";
self.gcTextView.textColor = [UIColor lightGrayColor];
gcTextView.layer.borderColor = [[UIColor whiteColor] CGColor];
然后使用此方法进行编辑 - >
- (void) textViewDidBeginEditing:(UITextView *) textView
{
[textView setText:@""];
self.gcTextView.textColor = [UIColor blackColor];
}
问题:我需要添加到这种方式
1)如果已修改的文字返回nil或textView
,我认为将占位符添加回@""
。
2)在textView
答案 0 :(得分:4)
为了在UITextView
中拥有占位符功能,我通常会这样做:
[self.gcTextView setText:@"placeholder"];
[self.gcTextView setTextColor:[UIColor lightGrayColor]];
[self.gcTextView setTag:100]; //start tag with default 100
- (void) textViewShouldBeginEditing:(UITextView *) textView
{
if(textView.tag == 100) {
[textView setTag:200];
[textView setText:@""];
[textView setTextColor:[UIColor blackColor];
}
}
- (void) textViewDidEndEditing:(UITextView *) textView
{
//handle text that has spaces as it's content (i.e. no characters)
NSString *strStrippedText = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if(strStrippedText.length == 0) {
[textView setTag:100];
[textView setText:@"Placeholder"];
[textView setTextColor:[UIColor lightGrayColor];
}
}
基本上,这都与我设置的标签有关
如果您将标签用于其他目的,那么这可能会破坏某些内容,因此您可以安全地修改bounces
属性并将其用作个人使用的指示器。
[self.gcTextView setText:@"placeholder"];
[self.gcTextView setTextColor:[UIColor lightGrayColor]];
[self.gcTextView setBounces:NO]; //NO for placeholder text
- (void) textViewShouldBeginEditing:(UITextView *) textView
{
if(textView.bounces == NO) {
[textView setText:@""];
[textView setTextColor:[UIColor blackColor];
[textView setBounces:YES]; //YES for non-placeholder text
}
}
- (void) textViewDidEndEditing:(UITextView *) textView
{
//handle text that has spaces as it's content (i.e. no characters)
NSString *strStrippedText = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if(strStrippedText.length == 0) {
[textView setText:@"Placeholder"];
[textView setTextColor:[UIColor lightGrayColor];
[textView setBounces:NO];
}
}
答案 1 :(得分:0)
我不得不将标签版本(IOS 9)更改为以下代码。
- (BOOL) textViewShouldBeginEditing:(UITextView *) textView //changed to bool
{
if(textView.tag == 100) {
[textView setTag:200];
[textView setText:@""];
[textView setTextColor:[UIColor blackColor]];
}
return YES; // added return value
}
- (void) textViewDidEndEditing:(UITextView *) textView
{
//handle text that has spaces as it's content (i.e. no characters)
NSString *strStrippedText = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if(strStrippedText.length == 0) {
[textView setText:UI_TEXT_HINT_BODY];
[textView setTextColor:[UIColor lightGrayColor]];
[textView setBounces:NO];
[textView setTag:100]; // reset to hint mode
}
}