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

标签 ios swift uitextview

我正在开发一个严重依赖 UITextView 的应用程序。期望的行为是当用户双击空格键时,光标将缩进 5 个空格。我该怎么做?

最佳答案

您应该使用检查短时间间隔的计时器和 UITextView 的 shouldChangeTextInRange 委托(delegate)方法,并编写空格字符串的条件。之后,您可以使用 UITextView 协议(protocol)之一 UITextInput 的 insertText 方法:

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
}

关于ios - 在 Swift 中,如何检测 UITextView 中空格键的双击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102882/

相关文章:

ios - iOS 中的原生动画

ios - 专注 Action 的时间延迟

ios - UITableView 设置为无选择

ios - Mapview委托(delegate)函数在关闭包含mapview的 View Controller 后继续运行

ios - UIImageView 的拉伸(stretch)属性有什么用。我如何使用此属性。?

ios - 使用 NSURLSession 上传多张图片

SwiftUI 多屏导航

ios - 使用自动布局的 UITextView 动态高度 - 每行新行的文本截断顶行

ios - UITextView 可点击标签辅助功能画外音问题

objective-c - 如何检测 NSString 中以 “@” 或 “#” 开头的单词?