Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

UITextViewをSwiftUIで用いる。

makeUIView, updateUIView, makeCoordinatorを実装する。Coordinatorはdelegateを処理する。

import UIKit
import Combine
// https://www.appcoda.com/swiftui-textview-uiviewrepresentable/
struct EditView: UIViewRepresentable {
    
    @Binding var text: String
    @Binding var textStyle:UIFont.TextStyle
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        
        textView.font = UIFont.preferredFont(forTextStyle: textStyle)
        textView.autocapitalizationType = .sentences
        textView.isSelectable = true
        textView.isUserInteractionEnabled = true
        textView.delegate = context.coordinator
        
        return textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
        uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator($text)
    }
}

class Coordinator: NSObject, UITextViewDelegate {
    var text: Binding<String>
    
    init(_ text:Binding<String>) {
        self.text = text
    }
    
    func textViewDidChange(_ textView: UITextView) {
        self.text.wrappedValue = textView.text
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
    }
}

使う側は単に呼び出す

struct ContentView: View {
    
    @State private var message = "x"
    @State private var textStyle = UIFont.TextStyle.body
    
    var body: some View {
        VStack(alignment: .leading) {
            Button(action: {
                UIApplication.shared.endEditing()
            }, label: {
                Text("Push")
            })
            Text(message)
            EditView(text: $message, textStyle: $textStyle)
        }
    }
}

今回、キーボードを下げるのは

import UIKit

extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

というextensionを用いた。