iOS - UITextField

时间:2023-03-09 00:27:39
iOS - UITextField

前言

	NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl <UITextInput, NSCoding>
@available(iOS 2.0, *) public class UITextField : UIControl, UITextInput, NSCoding

1、UITextField 的创建

  • Objective-C

    	// 实例化 UITextField 对象
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 200, 30)]; // 将 textField 加到 window 上显示出来
    [self.view addSubview:textField];
  • Swift

    	// 实例化 UITextField 对象
    let textField:UITextField = UITextField(frame: CGRectMake(20, 100, 200, 30)) // 将 textField 加到 window 上显示出来
    self.view.addSubview(textField)

2、UITextField 的设置

  • Objective-C

    	// 设置边框样式
    /*
    UITextBorderStyleNone, 无边框,默认
    UITextBorderStyleLine, 直线边框
    UITextBorderStyleBezel, 边框 + 阴影
    UITextBorderStyleRoundedRect 圆角矩形边框
    */
    textField.borderStyle = UITextBorderStyleLine; // 设置背景颜色
    /*
    默认是透明的
    */
    textField.backgroundColor = [UIColor yellowColor]; // 设置背景图片
    textField.background = [UIImage imageNamed:@"pic2"]; // 设置提示文字
    /*
    用户输入时自动消失
    */
    textField.placeholder = @"请输入用户名"; // 设置输入的字体颜色
    textField.textColor = [UIColor redColor]; // 设置文字对齐方式
    textField.textAlignment = NSTextAlignmentLeft; // 设置最小可缩小的字号
    textField.minimumFontSize = 10; // 自动调整文字大小
    /*
    自动调整文字的大小以适应 textField 的宽度
    */
    textField.adjustsFontSizeToFitWidth = YES; // 设置密文输入模式
    /*
    default is NO
    */
    textField.secureTextEntry = YES; // 设置显示清除按钮
    /*
    UITextFieldViewModeNever, // default
    UITextFieldViewModeWhileEditing,
    UITextFieldViewModeUnlessEditing,
    UITextFieldViewModeAlways
    */
    textField.clearButtonMode = UITextFieldViewModeWhileEditing; // 设置键盘样式
    /*
    UIKeyboardTypeDefault, // Default type for the current input method.
    UIKeyboardTypeASCIICapable, // Displays a keyboard which can enter ASCII characters,
    // non-ASCII keyboards remain active
    UIKeyboardTypeNumbersAndPunctuation, // Numbers and assorted punctuation.
    UIKeyboardTypeURL, // A type optimized for URL entry.
    UIKeyboardTypeNumberPad, // A number pad (0-9). Suitable for PIN entry.
    UIKeyboardTypePhonePad, // A phone pad (1-9, *, 0, #, with letters under the numbers).
    UIKeyboardTypeNamePhonePad, // A type optimized for entering a person's name or phone number.
    UIKeyboardTypeEmailAddress, // A type optimized for multiple email address entry.
    UIKeyboardTypeDecimalPad, // A number pad with a decimal point.
    UIKeyboardTypeTwitter, // A type optimized for twitter text entry (easy access to @ #)
    UIKeyboardTypeWebSearch, // A default keyboard type with URL-oriented addition.
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated
    */
    textField.keyboardType = UIKeyboardTypeDefault; // 设置返回键样式
    /*
    UIReturnKeyDefault,
    UIReturnKeyGo,
    UIReturnKeyGoogle,
    UIReturnKeyJoin,
    UIReturnKeyNext,
    UIReturnKeyRoute,
    UIReturnKeySearch,
    UIReturnKeySend,
    UIReturnKeyYahoo,
    UIReturnKeyDone,
    UIReturnKeyEmergencyCall,
    UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
    */
    textField.returnKeyType = UIReturnKeyJoin; // 设置输入的字母大小写模式
    /*
    UITextAutocapitalizationTypeNone,
    UITextAutocapitalizationTypeWords,
    UITextAutocapitalizationTypeSentences,
    UITextAutocapitalizationTypeAllCharacters,
    */
    textField.autocapitalizationType = UITextAutocapitalizationTypeWords; // 设置左右视图显示模式
    /*
    不设置模式,左右视图显示不出来 UITextFieldViewModeNever,
    UITextFieldViewModeWhileEditing,
    UITextFieldViewModeUnlessEditing,
    UITextFieldViewModeAlways
    */
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.rightViewMode = UITextFieldViewModeAlways; // 设置左右视图
    textField.leftView = label1;
    textField.rightView = label2; // 让 textField 获取第一响应
    /*
    打开应用程序或界面时直接弹出键盘
    */
    [textField becomeFirstResponder]; // 让 textField 放弃第一响应
    /*
    收起键盘
    */
    [textField resignFirstResponder]; // 设置 textField 的代理,需遵守协议 <UITextFieldDelegate>
    textField.delegate = self;
  • Swift

    	// 设置边框样式
    /*
    case None 无边框,默认
    case Line 直线边框
    case Bezel 边框 + 阴影
    case RoundedRect 圆角矩形边框
    */
    textField.borderStyle = .Line // 设置背景颜色
    /*
    默认是透明的
    */
    textField.backgroundColor = UIColor.yellowColor() // 设置背景图片
    textField.background = UIImage(named: "pic2") // 设置提示文字
    /*
    用户输入时自动消失
    */
    textField.placeholder = "请输入用户名" // 设置输入的字体颜色
    textField.textColor = UIColor.redColor() // 设置文字对齐方式
    textField.textAlignment = NSTextAlignment.Left // 设置最小可缩小的字号
    textField.minimumFontSize = 10 // 自动调整文字大小
    /*
    自动调整文字的大小以适应 textField 的宽度
    */
    textField.adjustsFontSizeToFitWidth = true // 设置密文输入模式
    /*
    default is NO
    */
    textField.secureTextEntry = true // 设置显示清除按钮
    /*
    case Never // default
    case WhileEditing
    case UnlessEditing
    case Always
    */
    textField.clearButtonMode = .WhileEditing // 设置键盘样式
    /*
    case Default // Default type for the current input method.
    case ASCIICapable // Displays a keyboard which can enter ASCII characters,
    // non-ASCII keyboards remain active
    case NumbersAndPunctuation // Numbers and assorted punctuation.
    case URL // A type optimized for URL entry.
    case NumberPad // A number pad (0-9). Suitable for PIN entry.
    case PhonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
    case NamePhonePad // A type optimized for entering a person's name or phone number.
    case EmailAddress // A type optimized for multiple email address entry.
    case DecimalPad // A number pad with a decimal point.
    case Twitter // A type optimized for twitter text entry (easy access to @ #)
    case WebSearch // A default keyboard type with URL-oriented addition. public static var Alphabet: UIKeyboardType { get } // Deprecated
    */
    textField.keyboardType = .Default // 设置返回键样式
    /*
    case Default
    case Go
    case Google
    case Join
    case Next
    case Route
    case Search
    case Send
    case Yahoo
    case Done
    case EmergencyCall
    case Continue
    */
    textField.returnKeyType = .Join // 设置输入的字母大小写模式
    /*
    case None
    case Words
    case Sentences
    case AllCharacters
    */
    textField.autocapitalizationType = .Words // 设置左右视图显示模式
    /*
    不设置模式,左右视图显示不出来 case Never
    case WhileEditing
    case UnlessEditing
    case Always
    */
    textField.leftViewMode = .Always
    textField.rightViewMode = .Always // 设置左右视图
    textField.leftView = label1
    textField.rightView = label2 // 让 textField 获取第一响应
    /*
    打开应用程序或界面时直接弹出键盘
    */
    textField.becomeFirstResponder() // 让 textField 放弃第一响应
    /*
    收起键盘
    */
    textField.resignFirstResponder() // 设置 textField 的代理,需遵守协议 UITextFieldDelegate
    textField.delegate = self

3、textField 协议方法

  • 协议方法,需遵守协议 UITextFieldDelegate,并设置代理

  • Objective-C

    	// 将要开始编辑,编辑开始前被调用
    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { return YES;
    } // 已经开始编辑,编辑开始后被调用,可监听键盘的弹出
    - (void)textFieldDidBeginEditing:(UITextField *)textField { } // 将要结束编辑,编辑结束前被调用
    - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { return YES;
    } // 已经结束编辑,编辑结束后被调用,可监听键盘的回收
    - (void)textFieldDidEndEditing:(UITextField *)textField { // 输出 textfield 中输入的内容
    NSLog(@"您输入的内容为:%@", textField.text);
    } // 是否允许文本修改,文本修改前被调用
    /*
    NO 不允许输入,YES 允许输入(默认)
    range:光标范围
    string:当前输入的内容
    */
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { return YES;
    } // 返回,键盘上的 return 键触摸后调用
    - (BOOL)textFieldShouldReturn:(UITextField *)textField { return YES;
    } // 清空,文本输入框中清除按钮被触摸时调用
    - (BOOL)textFieldShouldClear:(UITextField *)textField { return YES;
    }
  • Swift

    	// 将要开始编辑,编辑开始前被调用
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool { return true
    } // 已经开始编辑,编辑开始后被调用,可监听键盘的弹出
    func textFieldDidBeginEditing(textField: UITextField) { } // 将要结束编辑,编辑结束前被调用
    func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true
    } // 已经结束编辑,编辑结束后被调用,可监听键盘的回收
    func textFieldDidEndEditing(textField: UITextField) { // 输出 textfield 中输入的内容
    print("您输入的内容为:\(textField.text)")
    } // 是否允许文本修改,文本修改前被调用
    /*
    false 不允许输入,true 允许输入(默认)
    range:光标范围
    string:当前输入的内容
    */
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { return true
    } // 返回,键盘上的 return 键触摸后调用
    func textFieldShouldReturn(textField: UITextField) -> Bool { return true
    } // 清空,文本输入框中清除按钮被触摸时调用
    func textFieldShouldClear(textField: UITextField) -> Bool { return true
    }

4、textField 的键盘回收

  • Objective-C

    • 触摸手势回收

      • 用触摸手势或表格滚动方式回收键盘,触摸界面或滚动表格视图时键盘消失
      	// 单一 textField 回收键盘
      
      		// 让 textField 放弃第一响应,收起键盘
      [textField resignFirstResponder]; // 所有 textField 都回收键盘 [self.view endEditing:YES];
    • return 键回收

      • 用代理方式回收键盘(键盘上的 return 键回收键盘),需遵守协议 UITextFieldDelegate,并设置代理
      	// 设置 textField 的代理
      textField1.delegate = self;
      textField2.delegate = self; // UITextFieldDelegate 协议方法返回,键盘上的 return 键点击后调用
      - (BOOL)textFieldShouldReturn:(UITextField *)textField { UITextField *textField_1 = (id)[self.view viewWithTag:200];
      UITextField *textField_2 = (id)[self.view viewWithTag:300]; if (textField == textField_1) { // 让 textField_2 获取第一响应
      // 点击 textfield_1 上的 return 键时,输入光标自动跳转到 textfield_2 内
      [textField_2 becomeFirstResponder];
      }
      else{
      // 让 textField_2 放弃第一响应
      // 点击 textfield_2 上的 return 键时,键盘回收
      [textField_2 resignFirstResponder];
      } return YES;
      }
  • Swift

    • 触摸手势回收

      • 用触摸手势或表格滚动方式回收键盘,触摸界面或滚动表格视图时键盘消失
      	// 单一 textField 回收键盘
      
      		// 让 textField 放弃第一响应,收起键盘
      textField.resignFirstResponder() // 所有 textField 都回收键盘 self.view.endEditing(true)
    • return 键回收

      • 用代理方式回收键盘(键盘上的 return 键回收键盘),需遵守协议 UITextFieldDelegate,并设置代理
      	// 设置 textField 的代理
      textField1.delegate = self
      textField2.delegate = self // UITextFieldDelegate 协议方法返回,键盘上的 return 键点击后调用
      func textFieldShouldReturn(textField: UITextField) -> Bool { let textField_1:UITextField = self.view.viewWithTag(200) as! UITextField
      let textField_2:UITextField = self.view.viewWithTag(300) as! UITextField if textField == textField_1 { // 让 textField_2 获取第一响应
      // 点击 textfield_1 上的 return 键时,输入光标自动跳转到 textfield_2 内
      textField_2.becomeFirstResponder()
      }
      else{
      // 让 textField_2 放弃第一响应,点击 textfield_2 上的 return 键时,键盘回收
      textField_2.resignFirstResponder()
      } return true
      }

5、textField 视图的上升/下降

  • Objective-C

    • 用系统观察者控制

      • 可以获取到键盘的高度和键盘弹起和隐藏的时间

      • 多个观察者

        	// 添加系统通知观察者(检测键盘的显示与隐藏)
        
        	// 检测键盘的弹起
        [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardShow:)
        name:UIKeyboardWillShowNotification
        object:nil]; // 检测键盘的隐藏
        [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardHide:)
        name:UIKeyboardWillHideNotification
        object:nil]; // 键盘弹起事件处理
        - (void)keyboardShow:(NSNotification *)notification { // 取出键盘最终的高度
        CGFloat keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height; // 取出键盘弹出需要花费的时间
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 设置当前视图的 frame
        CGRect frame = self.view.frame;
        frame.origin.y = -keyboardHeight; [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
        }];
        } // 键盘隐藏事件处理
        - (void)keyboardHide:(NSNotification *)notification { // 取出键盘弹出需要花费的时间
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 设置当前视图的 frame
        CGRect frame = self.view.frame;
        frame.origin.y = 0; [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
        }];
        }
      • 单一观察者

        	// 添加系统通知观察者(检测键盘的 frame 改变)
        
        	[[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardWillChangeFrame:)
        name:UIKeyboardWillChangeFrameNotification
        object:nil]; // 键盘弹起隐藏事件处理
        - (void)keyboardWillChangeFrame:(NSNotification *)notification { // 取出键盘最终的 frame
        CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 取出键盘弹出需要花费的时间
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 设置当前视图的 frame
        CGRect frame = self.view.frame;
        frame.origin.y = -([UIScreen mainScreen].bounds.size.height - rect.origin.y); [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
        }];
        }
      • 视图上升或下降处理

        • 设置 frame

          	CGRect frame = self.view.frame;
          frame.origin.y = -keyboardHeight;
          [UIView animateWithDuration:duration animations:^{
          self.view.frame = frame;
          }];
        • 设置 约束值

          	self.bottomSpacing.constant = rect.size.height;
          [UIView animateWithDuration:duration animations:^{
          [self.view layoutIfNeeded];
          }];
        • 设置 transform 属性

          	[UIView animateWithDuration:duration animations:^{
          CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
          self.view.transform = CGAffineTransformMakeTranslation(0, -ty);
          }];
    • 用协议方法控制

      	// 开始编辑
      - (void)textFieldDidBeginEditing:(UITextField *)textField { // 获取当前视图的 frame
      CGRect frame = self.view.frame;
      frame.origin.y = -53; [UIView animateWithDuration:0.5 animations:^{
      self.view.frame = frame;
      }];
      } // 结束编辑
      - (void)textFieldDidEndEditing:(UITextField *)textField { CGRect frame = self.view.frame;
      frame.origin.y = 0; [UIView animateWithDuration:0.5 animations:^{
      self.view.frame = frame;
      }];
      }
  • Swift

    • 用系统观察者控制

      • 可以获取到键盘的高度和键盘弹起和隐藏的时间

      • 多个观察者

        	// 添加系统通知观察者(检测键盘的显示与隐藏)
        
        	// 检测键盘的弹起
        NSNotificationCenter.defaultCenter().addObserver(self,
        selector: #selector(UiTextField.keyboardShow(_:)),
        name: UIKeyboardWillShowNotification,
        object: nil) // 检测键盘的隐藏
        NSNotificationCenter.defaultCenter().addObserver(self,
        selector: #selector(UiTextField.keyboardHide(_:)),
        name: UIKeyboardWillHideNotification,
        object: nil) // 键盘弹起事件处理
        func keyboardShow(notification:NSNotification) { // 取出键盘最终的高度
        let keyboardHeight:CGFloat = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height)! // 取出键盘弹出需要花费的时间
        let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue // 设置当前视图的 frame
        var frame:CGRect = self.view.frame
        frame.origin.y = -keyboardHeight UIView.animateWithDuration(duration) {
        self.view.frame = frame
        }
        } // 键盘隐藏事件处理
        func keyboardHide(notification:NSNotification) { // 取出键盘弹出需要花费的时间
        let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue // 设置当前视图的 frame
        var frame:CGRect = self.view.frame
        frame.origin.y = 0 UIView.animateWithDuration(duration) {
        self.view.frame = frame
        }
        }
      • 单一观察者

        	// 添加系统通知观察者(检测键盘的 frame 改变)
        
        	NSNotificationCenter.defaultCenter().addObserver(self,
        selector: #selector(UiTextField.keyboardWillChangeFrame(_:)),
        name: UIKeyboardWillChangeFrameNotification,
        object: nil) // 键盘弹起隐藏事件处理
        func keyboardWillChangeFrame(notification:NSNotification) { // 取出键盘最终的高度
        let rect:CGRect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue())! // 取出键盘弹出需要花费的时间
        let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue // 设置当前视图的 frame
        var frame:CGRect = self.view.frame
        frame.origin.y = -(UIScreen.mainScreen().bounds.size.height - rect.origin.y) UIView.animateWithDuration(duration) {
        self.view.frame = frame
        }
        }
      • 视图上升或下降处理

        • 设置 frame

          	var frame:CGRect = self.view.frame
          frame.origin.y = -keyboardHeight
          UIView.animateWithDuration(duration) {
          self.view.frame = frame
          }
        • 设置 约束值

          	self.bottomSpacing.constant = rect.size.height
          UIView.animateWithDuration(duration) {
          self.view.layoutIfNeeded()
          }
        • 设置 transform 属性

          	UIView.animateWithDuration(duration) {
          let ty:CGFloat = UIScreen.mainScreen().bounds.size.height - rect.origin.y
          self.view.transform = CGAffineTransformMakeTranslation(0, -ty)
          }
    • 用协议方法控制

      	// 开始编辑
      func textFieldDidBeginEditing(textField: UITextField) { // 获取当前视图的 frame
      var frame:CGRect = self.view.frame
      frame.origin.y = -53 UIView.animateWithDuration(0.5) {
      self.view.frame = frame
      }
      } // 结束编辑
      func textFieldDidEndEditing(textField: UITextField) { var frame:CGRect = self.view.frame
      frame.origin.y = 0 UIView.animateWithDuration(0.5) {
      self.view.frame = frame
      }
      }

6、计算键盘高度

  • 不同型号的 iOS 设备的键盘尺寸:

     Type          | iPhone 6(s) Plus |  iPhone 6(s) |  iPhone 5(s/c)/4(s)/SE

    ------------------------|:----------------