简体   繁体   中英

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. The desired behavior is when a user double taps the spacebar, the cursor will indent 5 spaces. 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. When you receive two space inputs within a short time frame, you manipulate the textfield with the 5 spaces.

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. After that, you can use the insertText method of UITextInput, one of UITextView's protocols:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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