简体   繁体   English

在Swift中,如何检测UITextView中空格键的双击?

[英]In Swift, how do I detect a double tap from the spacebar in UITextView?

I'm working on an app that is heavily dependent on a UITextView. 我正在开发一个严重依赖UITextView的应用程序。 The desired behavior is when a user double taps the spacebar, the cursor will indent 5 spaces. 所需的行为是当用户双击空格键时,光标将缩进5个空格。 How would I do this? 我该怎么做?

Use the UIText​View​Delegate and in the text​View(UIText​View, should​Change​Text​In:​ NSRange, replacement​Text:​ String) function you keep track of the space inputs and the times. 使用UIText ViewDelegate并在文本View(UIText View中,应该在以下位置更改Text In:NSRange,replacement Text:String)函数可跟踪空间输入和时间。 When you receive two space inputs within a short time frame, you manipulate the textfield with the 5 spaces. 当您在短时间内收到两个空格输入时,可以使用5个空格来操纵文本字段。

You should use a timer which checks for short time intervals and the shouldChangeTextInRange delegate method for UITextView and write a condition for space strings. 您应该使用计时器检查较短的时间间隔,并使用UITextView的shouldChangeTextInRange委托方法并为空格字符串编写条件。 After that, you can use the insertText method of UITextInput, one of UITextView's protocols: 之后,可以使用UITextInput的insertText方法,UITextInput的协议之一:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " { 
        if isSecondSpace {
            (textView as UIKeyInput).insertText("     ") //5 spaces
        } else {
            isSecondSpace = true

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                self.isSecondSpace = false
            }
        }

        return false
    }

    return true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM