您的位置:首页 > 产品设计 > UI/UE

UITextView用法

2016-01-29 16:26 387 查看
简介

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 : 16.0f];
self.contentInset =  UIEdgeInsetMake(10.0f, 0.0f, 0.0f, 0.0f);

[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(10.0f, 0.0f, keyboardRect.size.height, 0.0f);
}

-(void) handleKeyBoardWillHide:(Notification *) notification{
self.myTextView.contentInset =UIEdgeInsetMake(10.0f, 0.0f, 0.0f, 0.0f);
}

//在该方法中开始监听键盘事件
-(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 : 16.0f];
[self.view addSubView: self.myTextView];
}

//在该方法中停止监听键盘事件,防止视图控制器在后台监听键盘事件
-(void) viewWillDisappear: (BOOL) paramAnimated{
[super viewWillDisappear];

[[NSNotificationCenter defaultCenter] removeObserver: self];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: