UITextView 除了顯示純文字,也能直接渲染 HTML 內容。這在需要顯示條款、說明文件、隱私權政策這類長篇格式文本時特別方便——內容由前端或法務以 HTML 撰寫,App 端不必逐行排版。本文示範如何載入專案內的本地 HTML 檔。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// 建立指向 Bundle 內 HTML 檔的 URL
NSURL *html = [[NSBundle mainBundle] URLForResource:@"right_obligations" withExtension:@"html"];
// 用 HTML 建立 attributedString
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithFileURL:html
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
// 建立 TextView 並套用 attributed string
UITextView *textView = [[UITextView alloc]
initWithFrame:CGRectMake(0, kHeaderHeight, kScreenWidth, kScreenHeight - kHeaderHeight)];
textView.editable = NO;
[textView setAttributedText:attrStr];
[self.view addSubview:textView];
}
關鍵是 NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType 這個選項,它告訴系統把檔案內容當作 HTML 解析,而非純文字。
// 初始化並定義大小 UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, 280, 30)]; textview.backgroundColor = [UIColor whiteColor]; // 背景色 textview.scrollEnabled = NO; // 內容超出邊框時是否允許滑動,預設 YES textview.editable = YES; // 是否允許編輯,預設 YES textview.delegate = self; // 設定代理 textview.font = [UIFont fontWithName:@"Arial" size:18.0]; textview.returnKeyType = UIReturnKeyDefault; // return 鍵類型 textview.keyboardType = UIKeyboardTypeDefault; // 鍵盤類型 textview.textAlignment = NSTextAlignmentLeft; // 文字對齊,預設靠左 textview.dataDetectorTypes = UIDataDetectorTypeAll; // 偵測電話、網址、地址等 textview.textColor = [UIColor blackColor]; textview.text = @"UITextView 詳解"; [self.view addSubview:textview];
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView; // 即將開始編輯 - (BOOL)textViewShouldEndEditing:(UITextView *)textView; // 即將結束編輯 - (void)textViewDidBeginEditing:(UITextView *)textView; // 已開始編輯 - (void)textViewDidEndEditing:(UITextView *)textView; // 已結束編輯 // 內容即將改變(回傳 NO 可攔下這次輸入) - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; - (void)textViewDidChange:(UITextView *)textView; // 內容已改變 - (void)textViewDidChangeSelection:(UITextView *)textView; // 焦點/選取範圍改變
在 textViewDidChange: 中計算文字高度並調整控件 frame:
- (void)textViewDidChange:(UITextView *)textView {
// 計算文字高度
CGSize constraintSize;
constraintSize.width = textView.frame.size.width - 16;
constraintSize.height = MAXFLOAT;
CGSize sizeFrame = [textView.text sizeWithFont:textView.font
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
// 重新調整 textView 的高度
textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y,
textView.frame.size.width, sizeFrame.height + 5);
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
if (range.location >= 100) {
return NO; // 限制輸入長度
}
if ([text isEqualToString:@"\n"]) {
return NO; // 禁止換行
}
return YES;
}
iPhone 的軟鍵盤沒有內建的收起鍵,因此需要自行處理。
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *done = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(dismissKeyBoard)];
self.navigationItem.rightBarButtonItem = done;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (void)dismissKeyBoard {
[self.textView resignFirstResponder];
}
若輸入框不需要換行功能,可以直接攔截換行字元:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
UIToolbar *topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView setBarStyle:UIBarStyleBlack];
UIBarButtonItem *btnSpace = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithTitle:@"Done" style:UIBarButtonItemStyleDone
target:self action:@selector(dismissKeyBoard)];
NSArray *buttonsArray = @[btnSpace, doneButton];
[topView setItems:buttonsArray];
// 把 topView 設為 textView 的輸入附件
[textView setInputAccessoryView:topView];
initWithFileURL:options: 會阻塞主執行緒,造成畫面卡頓。長文件建議改用 WKWebView 並在背景預處理。sizeWithFont: 已廢棄。新專案請改用 sizeThatFits: 或 boundingRectWithSize:options:attributes:context:。[done release] 屬於 MRC 寫法,若專案使用 ARC 則應移除這些呼叫。