-
簡介
UITextView控件用來顯示多行并且可滾動的文字内容;它可以顯示超出控件大小的内容;Iphone中的Note應用就是一個UITextView;
-
建立
在視圖控制器中建立一個UITextView屬性,然後在ViewDidLoad方法中執行個體化該控件,并設定文本内容、文字大小等屬性;
#import "MyViewController.h"
@interface MyViewController()
@property(nonatomic, strong) UITextView *myTextView;
@end
@implementation
-(void) viewDidLoad{
[super viewDidLoad];
self.myTextView = [[UITextView alloc] initWithFrame: self.view.bounds];
self.myTextView.text = @"please write some words here...";
self.myTextView.font = [UIFont systemFontOfSize : f];
self.contentInset = UIEdgeInsetMake(f, f, f, f);
[self.view addSubView: self.myTextView];
}
-
常見問題
在點選該控件編輯區域時,鍵盤會遮擋主底部一部分區域,使得使用者無法看到這一部分的内容。可以通過監聽以下事件來解決這個問題。
UIKeyboardWillShowNotification: 輸入鍵盤即将從textField或者textView中出現時觸發;
UIKeyboardDidShowNotification: 輸入鍵盤處于顯示狀态時觸發;
UIKeyboardWillHideNotification: 輸入鍵盤即将消失時觸發;
UIKeyboardDidHideNotification: 輸入鍵盤完全消失時觸發;
當鍵盤即将出現時,調整textView的位置。是以可以使用ContentInset屬性來予以解決。
-(void) handleKeyboardIDidShow:(Notification *) notification{
NSValue *keyboardRectAsObject = [[notification userInfo] objectForKey: UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = CGRectZero;
[keyboardRectAsObject getVlaue: &keyboardRect];
//設定文本的下間距等于鍵盤高度
self.myTextView.contentInset = UIEdgeInsetMake(f, f, keyboardRect.size.height, f);
}
-(void) handleKeyBoardWillHide:(Notification *) notification{
self.myTextView.contentInset =UIEdgeInsetMake(f, f, f, f);
}
//在該方法中開始監聽鍵盤事件
-(void) viewWillAppear:(BOOL) paramAnimated{
[super viewWillAppear: paramAnimated];
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector:(handleKeyboardDidShow:)]
name: UIKeyboardDidShowNotification
object: nil];
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector(handleKeyboardWillHide:)
name: UIKeyboardWillHideNotification
object: nil];
self.myTextView = [[UITextView alloc] initWithFrame: self.view.bounds];
self.myTextView.text = @"please write some words here... ";
self.myTextView.font = [UIFont systemFontOfSize : f];
[self.view addSubView: self.myTextView];
}
//在該方法中停止監聽鍵盤事件,防止視圖控制器在背景監聽鍵盤事件
-(void) viewWillDisappear: (BOOL) paramAnimated{
[super viewWillDisappear];
[[NSNotificationCenter defaultCenter] removeObserver: self];
}