İçeriğe geç

SwiftUI ile TextView Toolbar kullanımı

Merhabalar bu yazımda TextView nesnesi ile birlikte Toolbar kullanımını sizlerle paylaşacağım.

SwiftUI içerisinde bazı nesneleri kullanmak için UIViewRepresentable yardımı ile UIKit içerisindeki nesnelere erişmemiz gerekli. Bu yazıdada örneğini vereceğim TextView kullanırken klavye üzerinde aksiyonlar eklediğimiz toolbar nesnesini bu şekilde yaratmamız gerekli.

Aşağıdaki örnekte custom bir textview nesnesi yaratarak toolbar ve auto height işlemini gerçekleştirdik. Bunun için UITextView nesnesi ve Delegate metodları ile yazılmış UIViewRepresentable sınıfı nesnesi işimizi görecektir.

struct ContentView: View {
    
    @State var inputText: String = ""
    @State var containerHeight: CGFloat = 0
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()
            VStack {
                AutoSizeTextView(placeholder: "Message:", text: $inputText, containerHeight: $containerHeight) {
                    print("Done Action @")
                }
                .padding(.horizontal)
                .frame(height: containerHeight <= 100 ? containerHeight : 100)
                .background(Color.white)
                .cornerRadius(7)
                .padding()
            }
        }
    }
}
struct AutoSizeTextView: UIViewRepresentable {
    
    var placeholder: String
    @Binding var text: String
    @Binding var containerHeight: CGFloat
    var onEnd: (() -> Void)?
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.text = placeholder
        textView.textColor = .gray
        textView.backgroundColor = .clear
        textView.font = .systemFont(ofSize: 19)
        textView.delegate = context.coordinator
        
        let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 50)))
        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: context.coordinator, action: #selector(context.coordinator.keyboardDoneAction))
        toolBar.items = [spacer, doneButton]
        toolBar.sizeToFit()
        textView.inputAccessoryView = toolBar
        
        return textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        DispatchQueue.main.async {
            if containerHeight == 0 { containerHeight = uiView.contentSize.height }
        }
    }
    
    class Coordinator: NSObject, UITextViewDelegate {
        
        var parent: AutoSizeTextView
        
        init(parent: AutoSizeTextView) {
            self.parent = parent
        }
        
        @objc func keyboardDoneAction() {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            parent.onEnd?()
        }
        
        func textViewDidBeginEditing(_ textView: UITextView) {
            if textView.text == parent.placeholder {
                textView.text = ""
                textView.textColor = UIColor(Color.primary)
            }
        }
        
        func textViewDidChange(_ textView: UITextView) {
            parent.text = textView.text
            parent.containerHeight = textView.contentSize.height
        }
        
        func textViewDidEndEditing(_ textView: UITextView) {
            if textView.text == "" {
                textView.text = parent.placeholder
                textView.textColor = .gray
            }
        }
    }
}

 

Kategori:SwiftUI

İlk Yorumu Siz Yapın

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.

Copyright © 2022 Kenan Atmaca