swift – SwiftUI: Detecting delete key press in iOS


This is the best code that I came up with and it works very well however the text is very small and it uses UIKit. I you’re not a fan of it. You’ll have to stick with the text comparison logic.

import SwiftUI
import UIKit

struct ContentView: View {
@State private var text = ""

var body: some View {
    MyTextView(text: $text)
        .padding()
}
}

struct MyTextView: UIViewRepresentable {
@Binding var text: String

class Coordinator: NSObject, UITextViewDelegate {
    var parent: MyTextView
    
    init(parent: MyTextView) {
        self.parent = parent
    }
    
    func textViewDidChange(_ textView: UITextView) {
        parent.text = textView.text
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text.isEmpty && textView.text.isEmpty {
            print("Delete key pressed")
        }
        return true
    }
}

func makeCoordinator() -> Coordinator {
    Coordinator(parent: self)
}

func makeUIView(context: Context) -> UITextView {
    let textView = UITextView()
    textView.delegate = context.coordinator
    return textView
}

func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.text = text
}
}

Update:
I also made the comparison logic:

import SwiftUI

struct ContentView: View {

@State private var text = "Hello, World!"
@State private var old = "Hello, World!"

var body: some View {
    TextField("text" , text: $text)
        .onChange(of: text) {
            if text.count <= old.count {
                print("Deleted the letter: \(old.replacingOccurrences(of: text, with: ""))")
            }
            old = text
        }
}
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img