码迷,mamicode.com
首页 > 其他好文 > 详细

UITextView 与 keyboard 处理

时间:2015-06-01 11:47:34      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

通过向 NSNotificationCenter 注册观察者监听键盘事件,根据键盘状态,从而动态调整 UITextView的 edgeInsets

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UITextView *myTextView;
@end

@implementation ViewController

/* 1 */
//- (void)viewDidLoad{
//    [super viewDidLoad];
//    
//    self.myTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
//    self.myTextView.text = @"Some text here...";
//    self.myTextView.contentInset = UIEdgeInsetsMake(10.0f, 0.0f, 0.0f, 0.0f);
//    self.myTextView.font = [UIFont systemFontOfSize:16.0f];
//    [self.view addSubview:self.myTextView];
//    
//}
    
/* 2 */
- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{
    
    /* Get the frame of the keyboard */
    NSValue *keyboardRectAsObject =
    [[paramNotification userInfo]
     objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    /* Place it in a CGRect */
    CGRect keyboardRect = CGRectZero;
    
    [keyboardRectAsObject getValue:&keyboardRect];
    
    /* Give a bottom margin to our text view that makes it
     reach to the top of the keyboard */
    self.myTextView.contentInset =
    UIEdgeInsetsMake(0.0f,
                     0.0f,
                     keyboardRect.size.height,
                     0.0f);
}
    
- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{
    /* Make the text view as big as the whole view again */
    self.myTextView.contentInset = UIEdgeInsetsZero;
}
    
- (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 = @"Some text here...";
    self.myTextView.font = [UIFont systemFontOfSize:16.0f];
    [self.view addSubview:self.myTextView];
    
}
    
- (void) viewWillDisappear:(BOOL)paramAnimated{
    [super viewWillDisappear:paramAnimated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


UITextView 与 keyboard 处理

标签:

原文地址:http://my.oschina.net/u/255456/blog/423266

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!