UITextView 是 iOS 上的多行輸入元件。它天生沒有 placeholder 屬性,這是與 UITextField 最大的差異,也是新手最容易卡住的地方。這篇把屬性用法與 placeholder 自製方案一起整理。
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 180)];
textView.text = @"";
textView.font = [UIFont fontWithName:@"Arial" size:16.5f];
textView.textColor = [UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1.0f];
textView.backgroundColor = [UIColor colorWithRed:254/255.0f green:254/255.0f blue:254/255.0f alpha:1.0f];
textView.textAlignment = NSTextAlignmentLeft;
textView.scrollEnabled = YES;
textView.delegate = self;
textView.autocorrectionType = UITextAutocorrectionTypeNo;
textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
textView.keyboardType = UIKeyboardTypeDefault;
textView.returnKeyType = UIReturnKeyDefault;
這些屬性與 UITextField 完全相同:自動更正有 Default / No / Yes;自動大寫有 None / Words / Sentences / AllCharacters;鍵盤類型與 Return Key 的選項請參考 UITextField 的整理。
對齊方式同樣是 Left、Center、Right、Justified、Natural 五種。
做法是疊一個 UILabel 在上面,並在內容為空時顯示、有內容時清空:
// 提示標籤
UILabel *tip = [[UILabel alloc] initWithFrame:CGRectMake(16, 14, 320, 25)];
tip.text = @"您的意見是我們前進的最大動力,謝謝!";
tip.font = [UIFont fontWithName:@"Arial" size:16.5f];
tip.backgroundColor = [UIColor clearColor];
// 字數統計標籤
UILabel *count = [[UILabel alloc] initWithFrame:CGRectMake(270, 170, 35, 20)];
count.textAlignment = NSTextAlignmentRight;
count.font = [UIFont fontWithName:@"Arial" size:15.0f];
count.backgroundColor = [UIColor clearColor];
[self.view addSubview:textView];
[self.view addSubview:tip];
[self.view addSubview:count];
#pragma mark - UITextViewDelegate
// 限制輸入長度
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
return (range.location < 240);
}
// 內容變化時同步更新提示與字數
- (void)textViewDidChange:(UITextView *)textView {
count.text = [NSString stringWithFormat:@"%lu",
(unsigned long)(240 - textView.text.length)];
tip.text = (textView.text.length == 0) ? @"您的意見是我們前進的最大動力,謝謝!" : @"";
}
上述手刻方案需要自行處理位置、字型、多行換行與外觀。iOS 13 之後,UITextView 已內建 placeholder 與 placeholderColor 屬性,一行即可:
if (@available(iOS 13.0, *)) {
textView.placeholder = @"您的意見是我們前進的最大動力,謝謝!";
textView.placeholderColor = [UIColor grayColor];
}
若專案仍需支援舊版系統,也可以把提示 UILabel 的 frame 綁定在 textView 的內容邊界上,並在 textViewDidChange: 中切換 hidden,比改字串更直覺。
range.location < 240,在中文輸入法的候選字組合階段可能誤判。較穩妥的寫法是同時檢查 textView.text.length - range.length + text.length 是否超過上限。textContainerInset。UIKeyboardWillShowNotification 並調整 view 的 contentInset,或乾脆把整個表單放進 UIScrollView。shouldChangeTextInRange: 中的 \n。