(Swift&OC)UITextView的的使用技巧

作者: IIronMan | 来源:发表于2018-01-22 16:20 被阅读178次

    一、关键词

    • 1.1.弹性方向

      alwaysBounceVertical垂直
      alwaysBounceHorizontal 水平

    • 1.2.滑动UITextView键盘下去
      keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag

    • 1.3.输入框是否有内容

      hasText : 状态是truefalse

    • 1.4. UITextView上面添加view

      inputAccessoryView

    • 1.5. 自定义键盘

      inputView

    • 1.6.有关键盘的通知(设置动画节奏),建议多看看下面的代码注释

      • UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏

    二、Swift中的使用

    • 2.1.键盘上加一个view(JKTextViewController)

      import UIKit
      
      class JKTextViewController: UIViewController {
      
      override func viewDidLoad() {
        super.viewDidLoad()
        
        /**
            1.控制器的基本设置
         */
        title = "JKTextView"
        view.backgroundColor = UIColor.white
        self.edgesForExtendedLayout = []
        
        /**
            2.添加UITextView和提示内容以及键盘上的view
         */
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        textView.inputAccessoryView = jkInputAccessoryView
      }
      
      // MARK: UITextView 的创建
      private lazy var textView:UITextView = {
        
        let textview = UITextView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-64))
        textview.font = UIFont.systemFont(ofSize: 20)
        // 垂直水平方向有弹性
        textview.alwaysBounceVertical = true
        // 垂直方向滑动键盘下去
        textview.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return textview
      }()
      
      // MARK: UILabel 提示文本
      private lazy var placeholderLabel: UILabel = {
        
        let label = UILabel(frame: CGRect(x: 5, y: 9, width: UIScreen.main.bounds.width-10, height: 22))
        label.font = UIFont .systemFont(ofSize: 20)
        label.textColor = UIColor.red
        label.text = "分享新鲜事"
        return label
        
      }()
      
       // MARK: UIView 键盘上加个view
       private lazy var jkInputAccessoryView: UIView = {
        
         let inputView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
         inputView.backgroundColor = UIColor.green
         return inputView
        
       }()
      }
      
      // MARK: UITextView代理的实现
       extension JKTextViewController: UITextViewDelegate{
      
       func textViewDidChange(_ textView: UITextView) {
        
         /**
             hasText 可以判断UITextView是否有内容
          */
         placeholderLabel.isHidden = textView.hasText
      
         }
       }
      
    • 2.2.切换自定义键盘(JKTextViewController)

      import UIKit
      
      class JKTextViewController: UIViewController {
      
      override func viewDidLoad() {
        super.viewDidLoad()
        
        // 0.注册通知监听键盘弹出和消失
        NotificationCenter.default.addObserver(self, selector: #selector(JKTextViewController.keyboardChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        /**
            1.控制器的基本设置
         */
        title = "JKTextView"
        view.backgroundColor = UIColor.white
        self.edgesForExtendedLayout = []
        
        /**
            2.添加UITextView和提示内容以及键盘上的view
         */
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        /**
            3.输入框上面自定义一个view
         */
        view.addSubview(toolBar)
        toolBar.addSubview(toolBarBtn)
        
      }
      
       /**
           只要键盘改变就会调用
        */
       @objc func keyboardChange(notify: NSNotification)
       {
        // 1.取出键盘最终的rect
        let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let rect = value.cgRectValue
        
        // 2.修改工具条的约束
        // 弹出 : Y = 409 height = 258
        // 关闭 : Y = 667 height = 258
        // 667 - 409 = 258
        // 667 - 667 = 0
        
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        /*
         工具条回弹是因为执行了两次动画, 而系统自带的键盘的动画节奏(曲线) 7
         7在apple API中并没有提供给我们, 但是我们可以使用
         7这种节奏有一个特点: 如果连续执行两次动画, 不管上一次有没有执行完毕, 都会立刻执行下一次
         也就是说上一次可能会被忽略
         
         如果将动画节奏设置为7, 那么动画的时长无论如何都会自动修改为0.5
         
         UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏
         */
        // 1.取出键盘的动画节奏
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        UIView.animate(withDuration: duration.doubleValue) { () -> Void in
            
            // 2.设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.intValue)!)
            self.toolBar.frame.origin.y = rect.origin.y - 64 - 44
        }
        
        let anim = toolBar.layer.animation(forKey: "position")
        print("duration = \(String(describing: anim?.duration))")
      }
      
      // MARK: 切换键盘
      @objc func switchKeyBoard() {
        
        print("切换表情键盘")
        print(#function)
        // 结论: 如果是系统自带的键盘, 那么inputView = nil
        //      如果不是系统自带的键盘, 那么inputView != nil
        //        print(textView.inputView)
        
        // 1.关闭键盘
        textView.resignFirstResponder()
        
        // 2.设置inputView
        textView.inputView = (textView.inputView == nil) ? keyBoardView : nil
        
        // 3.从新召唤出键盘
        textView.becomeFirstResponder()
      }
      
       deinit
       {
         NotificationCenter.default.removeObserver(self)
       }
      
       // MARK: UITextView 的创建
       private lazy var textView:UITextView = {
        
        let textview = UITextView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-64))
        textview.font = UIFont.systemFont(ofSize: 20)
        // 垂直水平方向有弹性
        textview.alwaysBounceVertical = true
        // 垂直方向滑动键盘下去
        textview.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return textview
       }()
      
       // MARK: UILabel 提示文本
       private lazy var placeholderLabel: UILabel = {
        
        let label = UILabel(frame: CGRect(x: 5, y: 9, width: UIScreen.main.bounds.width-10, height: 22))
        label.font = UIFont .systemFont(ofSize: 20)
        label.textColor = UIColor.red
        label.text = "分享新鲜事"
        return label
        
       }()
      
       // MARK: UIView 键盘上加个view
       private lazy var toolBar: UIView = {
        
        let inputView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height-64-44, width: UIScreen.main.bounds.width, height: 44))
        inputView.backgroundColor = UIColor.green
        return inputView
        
       }()
      
       // MARK: UIView 键盘上加个view 上面加个button
       private lazy var toolBarBtn: UIButton = {
        
        let btn = UIButton(frame: CGRect(x: UIScreen.main.bounds.width-150, y: 0, width: 100, height: 44))
        btn.backgroundColor = UIColor.purple
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("切换键盘", for: UIControlState.normal)
        btn.addTarget(self, action: #selector(JKTextViewController.switchKeyBoard), for: UIControlEvents.touchUpInside)
        return btn
        
       }()
      
       // MARK: 自定义键盘
       private lazy var keyBoardView: UIView = {
        
        let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        keyboardView.backgroundColor = UIColor.brown
        return keyboardView
        
        }()
      }
      
      // MARK: UITextView代理的实现
      extension JKTextViewController: UITextViewDelegate{
      
        func textViewDidChange(_ textView: UITextView) {
          /**
              hasText 可以判断UITextView是否有内容
           */
           placeholderLabel.isHidden = textView.hasText
        }
      }
      

    三、OC中的使用

    • 3.1.键盘上加一个view(TestViewController)

      #import "TestViewController.h"
      #define CIO_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
      #define CIO_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
      #define TitleBlackCOLOR [UIColor colorWithRed:(51)/255.0 green:(51)/255.0 blue:(51)/255.0 alpha:1]
      #define backGayCOLOR [UIColor colorWithRed:(232)/255.0 green:(232)/255.0 blue:(232)/255.0 alpha:1]
      @interface TestViewController ()<UITextViewDelegate>
      
      /**
         UITextView输入框的创建
       */
      @property(nonatomic,strong) UITextView *jkTextView;
      /**
       提示内容
      */
      @property(nonatomic,strong) UILabel *placeholderLabel;
      /**
        键盘上添加一个view
       */
      @property(nonatomic,strong) UIView *jkInputAccessoryView;
      
      @end
      
      @implementation TestViewController
      
      - (void)viewDidLoad {
         [super viewDidLoad];
      
         self.edgesForExtendedLayout = UIRectEdgeNone;
         self.view.backgroundColor = [UIColor whiteColor];
      
         [self.view addSubview:self.jkTextView];
         [self.jkTextView addSubview:self.placeholderLabel];
         self.jkTextView.inputAccessoryView = self.jkInputAccessoryView;
      
      }
      
      #pragma mark  textview的变化
      -(void)textViewDidChange:(UITextView *)textView{
      
         self.placeholderLabel.hidden = textView.hasText;
      }
      
      -(UITextView *)jkTextView{
      
        if (!_jkTextView) {
      
          _jkTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, CIO_SCREEN_WIDTH,CIO_SCREEN_HEIGHT-64)];
          [_jkTextView becomeFirstResponder];
          // UITextView可以垂直滑动弹出键盘
          _jkTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
          _jkTextView.alwaysBounceVertical = YES;
          _jkTextView.delegate = self;
          _jkTextView.backgroundColor = [UIColor whiteColor];
          _jkTextView.textColor = TitleBlackCOLOR;
          _jkTextView.font = [UIFont systemFontOfSize:16.f];
         }
        return _jkTextView;
      }
      
      -(UILabel *)placeholderLabel{
      
          if (!_placeholderLabel) {
      
             _placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 9, CIO_SCREEN_WIDTH-10, 22)];
             _placeholderLabel.text = @"分享新鲜事";
             _placeholderLabel.textColor = backGayCOLOR;
             _placeholderLabel.font = [UIFont systemFontOfSize:20];
           }
      
        return _placeholderLabel;
      }
      
      -(UIView *)jkInputAccessoryView{
      
         if (!_jkInputAccessoryView) {
      
            _jkInputAccessoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CIO_SCREEN_WIDTH, 44)];
            _jkInputAccessoryView.backgroundColor = [UIColor redColor];
          }
         return _jkInputAccessoryView;
       }
      
      @end
      
    • 3.2.切换自定义键盘(TestViewController)

      #import "TestViewController.h"
      #import "UIView+JKUiviewExtension.h"
      
      #define CIO_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
      #define CIO_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
      #define TitleBlackCOLOR [UIColor colorWithRed:(51)/255.0 green:(51)/255.0 blue:(51)/255.0 alpha:1]
      #define backGayCOLOR [UIColor colorWithRed:(232)/255.0 green:(232)/255.0 blue:(232)/255.0 alpha:1]
      
      @interface TestViewController ()<UITextViewDelegate>
      
       /**
           UITextView输入框的创建
         */
         @property(nonatomic,strong) UITextView *jkTextView;
         /**
            提示内容
          */
         @property(nonatomic,strong) UILabel *placeholderLabel;
         /**
             键盘上添加一个view
          */
          @property(nonatomic,strong) UIView *tooBarView;
          @property(nonatomic,strong) UIButton *tooBarViewBtn;
      
      // 自定义键盘
      @property(nonatomic,strong) UIView *keyBoardView;
      
      @end
      
      @implementation TestViewController
      
      - (void)viewDidLoad {
        [super viewDidLoad];
      
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.view.backgroundColor = [UIColor whiteColor];
      
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
      
        [self.view addSubview:self.jkTextView];
        [self.jkTextView addSubview:self.placeholderLabel];
        [self.view addSubview: self.tooBarView];
        [self.tooBarView addSubview:self.tooBarViewBtn];
      }
      
       #pragma mark 切换键盘
       -(void)switchKeyBoard{
      
         // 1.关闭键盘
         [self.jkTextView resignFirstResponder];
      
         // 2.设置inputView
         self.jkTextView.inputView = (self.jkTextView.inputView == nil) ? self.keyBoardView : nil;
      
        // 3.从新召唤出键盘
        [self.jkTextView becomeFirstResponder];
       }
      
       #pragma mark 监听键盘
       //实现接收到通知时的操作
       -(void)keyBoardChange:(NSNotification *)notification
       {
         //获取键盘弹出或收回时frame
         CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
      
         //获取键盘弹出所需时长
        float duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
      
        NSLog(@"键盘的弹出的时间=%lf",duration);
      
        /*
          工具条回弹是因为执行了两次动画, 而系统自带的键盘的动画节奏(曲线) 7
          7在apple API中并没有提供给我们, 但是我们可以使用
          7这种节奏有一个特点: 如果连续执行两次动画, 不管上一次有没有执行完毕, 都会立刻执行下一次
          也就是说上一次可能会被忽略
      
          如果将动画节奏设置为7, 那么动画的时长无论如何都会自动修改为0.5
      
          UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏
        */
       // 1.取出键盘的动画节奏
       float curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] floatValue];
      
       [UIView animateWithDuration:duration animations:^{
        
        // 2.设置动画节奏
        [UIView setAnimationCurve:curve];
        
        self.tooBarView.y = keyboardFrame.origin.y - 64 - 44;
        
       }];
      }
      
      #pragma mark  textview的变化
      -(void)textViewDidChange:(UITextView *)textView{
      
          self.placeholderLabel.hidden = textView.hasText;
      }
      
      -(UITextView *)jkTextView{
      
         if (!_jkTextView) {
        
        _jkTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, CIO_SCREEN_WIDTH,CIO_SCREEN_HEIGHT-64)];
        [_jkTextView becomeFirstResponder];
        // UITextView可以垂直滑动弹出键盘
        _jkTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _jkTextView.alwaysBounceVertical = YES;
        _jkTextView.delegate = self;
        _jkTextView.backgroundColor = [UIColor whiteColor];
        _jkTextView.textColor = TitleBlackCOLOR;
        _jkTextView.font = [UIFont systemFontOfSize:16.f];
      }
      
       return _jkTextView;
      }
      
      -(UILabel *)placeholderLabel{
      
         if (!_placeholderLabel) {
        
         _placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 9, CIO_SCREEN_WIDTH-10, 22)];
         _placeholderLabel.text = @"分享新鲜事";
         _placeholderLabel.textColor = backGayCOLOR;
         _placeholderLabel.font = [UIFont systemFontOfSize:20];
        }
      
       return _placeholderLabel;
      }
      
      -(UIView *)tooBarView{
      
         if (!_tooBarView) {
      
           _tooBarView = [[UIView alloc]initWithFrame:CGRectMake(0, CIO_SCREEN_HEIGHT-64-44, CIO_SCREEN_WIDTH, 44)];
           _tooBarView.backgroundColor = [UIColor redColor];
         }
        return _tooBarView;
       }
      
       -(UIButton *)tooBarViewBtn{
      
          if (!_tooBarViewBtn) {
        
             _tooBarViewBtn = [[UIButton alloc]initWithFrame:CGRectMake(CIO_SCREEN_WIDTH-150, 0, 100, 44)];
             [_tooBarViewBtn addTarget:self action:@selector(switchKeyBoard) forControlEvents:UIControlEventTouchUpInside];
             [_tooBarViewBtn setTitle:@"切换键盘" forState:UIControlStateNormal];
             _tooBarViewBtn.backgroundColor = [UIColor purpleColor];
          }
         return _tooBarViewBtn;
       }
      
       -(UIView *)keyBoardView{
      
           if (!_keyBoardView) {
        
               _keyBoardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CIO_SCREEN_WIDTH, 100)];
              _keyBoardView.backgroundColor = [UIColor brownColor];
           }
      
         return _keyBoardView;
       }
      
       @end
      

    相关文章

      网友评论

        本文标题:(Swift&OC)UITextView的的使用技巧

        本文链接:https://www.haomeiwen.com/subject/vzxlaxtx.html