【问题标题】:want to know ever time while pressing on keyboard back button during textfield editing ios想知道在文本字段编辑 ios 期间按下键盘后退按钮的时间
【发布时间】:2017-07-27 07:27:09
【问题描述】:

在 OTP 中,使用了四个文本字段。按下键盘后退按钮时将光标移动到上一个文本字段?

【问题讨论】:

  • 你的问题不清楚
  • 正如@Anbu.Karthik 提到的,问题应该很清楚......
  • @AhmadF - tanx 供您编辑,真的很高兴,请检查我的答案一次

标签: ios swift swift3 keyboard uitextfield


【解决方案1】:

要检测 UITextField 中的退格事件,首先需要为 UITextField 设置一个委托并将其设置为 self。

 class ViewController: UIViewController,UITextFieldDelegate

 self.textField.delegate = self

然后你使用下面的委托方法来检测是否按下了退格键

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let char = string.cString(using: String.Encoding.utf8)
    let isBackSpace: Int = Int(strcmp(char, "\u{8}"))
    if isBackSpace == -8 {
        print("Backspace was pressed")
    }
            return true
}

基本上此方法检测您正在按下(或刚刚按下)的按钮。 此输入以 NSString 的形式出现。我们将此 NSString 转换为 C char 类型,然后将其与传统的退格字符 (\u{8}) 进行比较。那么如果这个strcmp等于-8,我们就可以把它检测为退格了。

选择 2

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if (string.characters.count ) == 0 {
        //Delete any cases
        if range.length > 1 {
            //Delete whole word
        }
        else if range.length == 1 {
            //Delete single letter
        }
        else if range.length == 0 {
            //Tap delete key when textField empty
        }
    }
   return true
 }

【讨论】:

  • 不是简单地检查替换字符串是否等于 "" 也可以吗?
  • @Rikh - 它只检查是否为空,请参阅我的 cmets Basically this method detects which button you are pressing (or have just pressed),它
【解决方案2】:

创建UITextField 的子类。然后覆盖deleteBackward 方法。最后通过确认BackSpaceDelegate 协议自定义delegate 来检测目标类中的退格。下面给大家演示一下:

protocol BackSpaceDelegate {
    func deleteBackWord(textField: CustomTextField)
}

class CustomTextField: UITextField {
    var backSpaceDelegate: BackSpaceDelegate?
    override func deleteBackward() {
        super.deleteBackward()
        // called when textfield is empty. you can customize yourself.
        if text?.isEmpty ?? false {
             backSpaceDelegate?.deleteBackWord(textField: self)
        }
    }
}
class YourViewController: UIViewController, BackSpaceDelegate {

    func deleteBackWord(textField: CustomTextField) {
        /// do your stuff here. That means resign or become first responder your expected textfield.
    }
}

希望这会对你有所帮助。

【讨论】:

    【解决方案3】:

    检查 textFieldShouldChangeTextInRange 中的 'string' 参数(你有名字,不是吗?)。如果为空,则点击了“退格”按钮。

    如果文本字段的“字符串”参数和“文本”属性均为空,则可以移至上一个文本字段。

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多