iOS 怎麼給UITextView新增佔位符文字
阿新 • • 發佈:2019-01-02
起初,方法是在cell.contentView上加一個label,在UITextView開始編輯時在代理方法裡隱藏label,結束編輯時如果UITextView沒文字,再把label顯示出來。相比如下方法顯得麻煩。
下面是通過runtime打印發現的UITextView裡有佔位符私有變數,可通過KVC直接設定一個佔位符,相對簡單,而且是可以釋出通過的。
// 通過執行時,發現UITextView有一個叫做“_placeHolderLabel”的私有變數 unsigned int count = 0; Ivar *ivars = class_copyIvarList([UITextView class], &count); for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; const char *name = ivar_getName(ivar); NSString *objcName = [NSString stringWithUTF8String:name]; NSLog(@"%d : %@",i,objcName); }
static NSString *questionCellID = @"questionCellID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:questionCellID]; cell.selectionStyle = UITableViewCellSelectionStyleNone; UITextView *questionTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 0, WID-30, 120)]; questionTV.font = [UIFont systemFontOfSize:12]; questionTV.textColor = [UIColor colorWithHexString:@"323232"]; questionTV.tag = 70; [cell.contentView addSubview:questionTV]; // _placeholderLabel UILabel *placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 12, CGRectGetWidth(questionTV.frame)-10, 14)]; placeHolderLabel.text = @"請描述您的病史、家族史及想要諮詢的主題"; placeHolderLabel.numberOfLines = 0; placeHolderLabel.textColor = [UIColor colorWithHexString:@"9a9a9a"]; placeHolderLabel.font = [UIFont systemFontOfSize:10]; placeHolderLabel.tag = 90; [cell.contentView addSubview:placeHolderLabel]; } UITextView *questionTV = (UITextView *)[cell.contentView viewWithTag:70]; questionTV.delegate = self; questionTV.text = _question; UILabel *placeHolderLabel = (UILabel *)[cell.contentView viewWithTag:90]; placeHolderLabel.hidden = (_question.length > 0 ? YES : NO); return cell;
補充:經測試,上面的用KVC設定私有變數的方法,在iOS8上會崩掉,檢視runtime列印的變數名沒有_placeholderLabel,所以,還是老老實實往cell上加一個label吧。
設定textView的代理,然後加下面的程式碼
#pragma mark - UITextViewDelegate -(void)textViewDidChange:(UITextView *)textView { _question = textView.text; UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4]]; UILabel *placeHolderLabel = (UILabel *)[cell.contentView viewWithTag:90]; if (textView.text.length == 0){ placeHolderLabel.hidden = NO; }else{ placeHolderLabel.hidden = YES; } }