@property (nonatomic, strong) UITextView *textView;
self.textView = [[UITextView alloc] initWithFrame:self.view.frame];
self.textView.textColor = [UIColor blackColor];
self.textView.font = [UIFont fontWithName:@"Arial" size:18.0];
self.textView.delegate = self;
self.textView.backgroundColor = [UIColor whiteColor];
self.textView.text = @"hehe";
self.textView.returnKeyType = UIReturnKeyDefault;
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.scrollEnabled = YES;
- (void)textViewDidBeginEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(getOverEditing)];
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (void)getOverEditing {
[self.textView resignFirstResponder];
}
UITextView 的 returnKeyType 在實務中經常被忽略,因為多行輸入的回車本意是換行。但如果你的場景不需要換行,可以攔截它:
- (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)];
UIBarButtonItem *cancelButton =
[[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone
target:self
action:@selector(dismissKeyBoard)];
[topView setItems:@[cancelButton]];
[self.textView setInputAccessoryView:topView];
- (void)dismissKeyBoard {
[self.textView resignFirstResponder];
}
系統默認的「拷貝 / 粘貼 / 全選」菜單是可以擴充的,通過 UIMenuController 加入自己的菜單項。
- (void)viewDidLoad {
[super viewDidLoad];
self._textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, 300, 200)];
[self.view addSubview:_textView];
UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"我是自定義的菜單"
action:@selector(didClickCustomMenuAction)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:@[menuItem]];
}
// 告訴系統哪些動作可以出現在菜單裡
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == @selector(didClickCustomMenuAction) || action == @selector(copy:)) {
if (_textView.selectedRange.length > 0) {
return YES;
}
}
return NO;
}
- (void)didClickCustomMenuAction {
NSLog(@"%@", NSStringFromSelector(_cmd));
}
關鍵在 canPerformAction:withSender:——只有返回 YES 的動作才會顯示。實踐中常見的擴展是「高亮」「翻譯」「收藏」這類基於選中文本的快捷操作。
有時候我們需要 UILabel 那樣的純展示效果,但又想保留 UITextView 自帶的複製、粘貼、選擇能力。此時只需關掉兩個屬性:
textView.editable = NO; // 不可編輯
textView.scrollEnabled = NO; // 不可滾動
問題往往出在需要計算文字尺寸並據此設置 UITextView 高度的時候。這種做法在 UILabel 上一切正常,換到 UITextView 卻總是顯示不全——高度寫大了留白,寫小了截斷。
UIFont *font = [UIFont systemFontOfSize:14.0f];
[textView setText:content];
CGSize textSize = [content sizeWithFont:font
constrainedToSize:CGSizeMake(200, 2000)
lineBreakMode:UILineBreakModeCharacterWrap];
textView.frame = CGRectMake(articleLabel.frame.origin.x,
articleLabel.frame.origin.y,
textSize.width,
textSize.height);
根因在於 UITextView 內部自帶 textContainerInset,默認是上 8、左 8、下 8、右 8,這部分內邊距並不包含在 sizeWithFont 的計算結果裡。把內邊距改成負值來抵消,或者乾脆把 inset 歸零後重新計算,都能解決:
[self.articleLabel setContentInset:UIEdgeInsetsMake(-10, -5, -15, -5)]; // 調整內邊距
[self.articleLabel setTextAlignment:NSTextAlignmentLeft]; // 左對齊
上面的 sizeWithFont:constrainedToSize: 系列方法在 iOS 7 之後已被標記廢棄。新項目應改用 TextKit 的尺寸計算方式:
CGRect bounds = CGRectMake(0, 0, 200, 0);
UITextView *tv = [[UITextView alloc] initWithFrame:bounds];
tv.text = content;
tv.layoutManager.allowsNonContiguousLayout = NO;
CGFloat height = [tv sizeThatFits:CGSizeMake(200, CGFLOAT_MAX)].height;
或者直接使用 boundingRectWithSize:options:attributedString:constraints: 配合 NSAttributedString 計算。若使用 Auto Layout,讓 UITextView 的 scrollEnabled 為 NO 並設置合適的 Content Hugging 與 Compression Resistance 優先級,系統就會自動撐開高度,完全不需要手動算。