多行輸入框是聊天、評論、地址填寫的共同需求,而 UITextView 偏偏沒有 placeholder 屬性(不像 UITextField)。實務上最直覺的做法是「用文字顏色變化模擬提示文字」:未聚焦且內容為空時顯示灰色提示,一旦開始編輯就清空並換成正常顏色。
透過切換 UITextView 的文字與文字顏色達到 placeholder 效果;鍵盤遮擋則用調整 UITableView 的 contentOffset 來避開。
textView = [[UITextView alloc] init]; textView.font = [UIFont systemFontOfSize:14]; textView.frame = CGRectMake(10, 0, DEVICE_WIDTH - 20, 56); textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; textView.backgroundColor = [UIColor clearColor]; textView.textColor = [UIColor colorWithHexString:@"#999999"]; // 提示文字用淺灰 textView.delegate = self; textView.text = @"請在這裡輸入"; [self.view addSubview:textView];
#pragma mark ----- UITextView delegate -----
// 開始編輯:清空提示文字,同時把列表上推讓出鍵盤空間
- (void)textViewDidBeginEditing:(UITextView *)textView {
[tableview setContentOffset:CGPointMake(0, 100) animated:YES];
if ([textView.text isEqualToString:@"請在這裡輸入"]) {
textView.textColor = [UIColor colorWithHexString:@"#77FF00"];
textView.text = @"";
}
}
// 結束編輯:內容為空就把提示文字放回去,並把列表復位
- (void)textViewDidEndEditing:(UITextView *)textView {
if (textView.text.length == 0 || [textView.text isEqualToString:@""]) {
textView.textColor = [UIColor colorWithHexString:@"#999999"];
textView.text = @"請在這裡輸入";
} else {
detailAddress.text = textView.text;
}
[tableview setContentOffset:CGPointMake(0, 0) animated:YES];
}
用「假裝成內容的提示文字」實作 placeholder 雖然簡單,但有兩個明顯缺點:一是使用者有可能把提示文字當成真的內容送出去(程式的判斷一漏就出事);二是提示文字被算進 length,做字數統計時容易出錯。
更穩健的作法是把提示文字畫在輸入框上層:額外放一個 UILabel 當提示,只在「內容為空且未取得焦點」時顯示它,並監聽 UITextViewDelegate 與 UITextDidChangeNotification 來切換顯示與隱藏。這樣 textView.text 永遠只承載使用者真正的輸入,邏輯乾淨得多。
// 監聽內容變化,即時切換提示 label
- (void)textViewDidChange:(UITextView *)textView {
_placeholderLabel.hidden = (textView.text.length > 0);
}
直接 setContentOffset:(0, 100) 之所以不理想,是因為鍵盤高度會隨輸入法(中文候選列、表情鍵盤)與外接鍵盤而改變,寫死數字在不同情境下都會出錯。建議改成監聽鍵盤通知,從 userInfo 取出實際高度再決定要上推多少:
- (void)keyboardWillShow:(NSNotification *)note {
CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardHeight = keyboardFrame.size.height;
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
tableview.contentInset = insets;
tableview.scrollIndicatorInsets = insets;
}
- (void)keyboardWillHide:(NSNotification *)note {
tableview.contentInset = UIEdgeInsetsZero;
tableview.scrollIndicatorInsets = UIEdgeInsetsZero;
}
用 contentInset 而不是 contentOffset 的優點是:它不破壞使用者目前的捲動位置,鍵盤收起後也不必特別復位。