article

Tuesday, August 10, 2021

SwiftUI TextEditor How to set Placeholder and background

SwiftUI TextEditor How to set Placeholder and background
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var text = ""
   var body: some View {
       NavigationView {
               VStack(alignment: .leading){
                   Text("How are you feeing today?")
                       .font(.title)
                   CustomTextEditor.init(placeholder: "Start typing..", text: $text)
                       .font(.body)
                       .background(Color(UIColor.systemGray6))
                       .accentColor(.green)
                       .frame(height: 400)
                       .cornerRadius(8)
                   Spacer()
               }.padding()
   
           .navigationTitle("Navigation")
       }
   }
}

struct CustomTextEditor: View {
    let placeholder: String
    @Binding var text: String
    let internalPadding: CGFloat = 5
    var body: some View {
        ZStack(alignment: .topLeading) {
            if text.isEmpty  {
                Text(placeholder)
                    .foregroundColor(Color.primary.opacity(0.25))
                    .padding(EdgeInsets(top: 7, leading: 4, bottom: 0, trailing: 0))
                    .padding(internalPadding)
            }
            TextEditor(text: $text)
                .padding(internalPadding)
        }.onAppear() {
            UITextView.appearance().backgroundColor = .clear
        }.onDisappear() {
            UITextView.appearance().backgroundColor = nil
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post