UITextView 是 iOS 開發中幾乎天天會用到的控件。實務上常見一個需求:意見反饋欄位要在首行前面顯示一段提示文字(例如「*您的意見」),使用者輸入的內容接續在後方,同時在未輸入時顯示一行淺色提示,一開始打字就自動隱藏。本文示範如何一次做到這兩個效果。
NSParagraphStyle 的 firstLineHeadIndent 讓第一行內文起始位置推開,數值需與標籤寬度對齊。textViewDidChange:,內容為空時顯示、有內容時隱藏。
#import "UItextviewSuoJinViewController.h"
@interface UItextviewSuoJinViewController () <UITextViewDelegate> {
// 意見內容
UITextView *contentTextView;
// 覆蓋在 UITextView 上的提示標籤
UILabel *promptLabel;
}
@end
@implementation UItextviewSuoJinViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
// 意見內容
contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, kHeaderHeight, kScreenWidth, 86)];
contentTextView.font = FONT(13);
contentTextView.delegate = self;
[self.view addSubview:contentTextView];
// 首行的提示標題
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, 60, 35)];
contentLabel.font = FONT(13);
contentLabel.text = @"*您的意見";
[contentTextView addSubview:contentLabel];
// 覆蓋在 UITextView 上的 placeholder
promptLabel = [[UILabel alloc] init];
promptLabel.frame = CGRectMake(5, 5, 200, 25);
promptLabel.text = @" 請輸入意見";
promptLabel.enabled = NO;
promptLabel.backgroundColor = [UIColor clearColor];
promptLabel.font = [UIFont systemFontOfSize:13];
promptLabel.textColor = RGB(245, 245, 245);
[contentTextView addSubview:promptLabel];
// 把星號改成紅色
NSMutableAttributedString *contentStr =
[[NSMutableAttributedString alloc] initWithString:contentLabel.text];
[contentStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, 1)];
contentLabel.attributedText = contentStr;
}
#pragma mark - UITextView 的代理方法
- (void)textViewDidChange:(UITextView *)textView {
if (textView.text.length == 0) {
promptLabel.hidden = NO;
} else {
promptLabel.hidden = YES;
}
// 首行縮進
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 3; // 行間距
// paragraphStyle.maximumLineHeight = 60; // 最大行高
paragraphStyle.firstLineHeadIndent = 93.f; // 首行縮進寬度
paragraphStyle.alignment = NSTextAlignmentJustified;
NSDictionary *attributes = @{
NSFontAttributeName: [UIFont systemFontOfSize:13],
NSParagraphStyleAttributeName: paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc]
initWithString:textView.text
attributes:attributes];
}
@end
firstLineHeadIndent 設為 93,是為了讓內文避開左側那個 60 點寬的提示標籤。調整標籤寬度時,這個數值也要跟著改。NSAttributedString 設定 paragraphStyle 來定位。attributedText。注意每次 textViewDidChange 都會重建一次 attributed string,內容很長時可能有效能負擔,可視情況只在需要時更新。UITextField 或自行封裝一個可重用的 subclass。把這段程式碼貼進自己的專案調整一下座標,就能看到效果。