UITextView用法

  • 简介

    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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值