1

I am trying to style a Text Editor in SwiftUI to look like a Material Design element. Currently, I'm struggling with the floating label. I cannot figure out how to capture the editing state of Text Editor. This is the code of the app:

struct FloatingTextEditor: View {
let textFieldHeight: CGFloat = 168
private let placeHolderText: String
@Binding var text: String
@State private var isEditing = false
public init(placeHolder: String,
            text: Binding<String>) {
    self._text = text
    self.placeHolderText = placeHolder
}
var shouldPlaceHolderMove: Bool {
    isEditing || (text.count != 0)
}
var body: some View {
    ZStack(alignment: .topLeading) {
        TextEditor(text: $text)
            .onTapGesture {
            isEditing = true
        }
            .padding()
            .frame(height: textFieldHeight)
            .paragraph()
            .overlay(RoundedRectangle(cornerRadius: 4)
                        .stroke(Color.medium, lineWidth: 1))
            .animation(.linear)
        
        Text(placeHolderText)
        .foregroundColor(Color.medium)
            .background(Color(UIColor.systemBackground))
        .padding(shouldPlaceHolderMove ?
                 EdgeInsets(top: 0, leading:15, bottom: (textFieldHeight+30), trailing: 0) :
                 EdgeInsets(top: 0, leading:15, bottom: (textFieldHeight-10), trailing: 0))
            .scaleEffect(shouldPlaceHolderMove ? 1.0 : 0.8)
        .animation(.linear)
    }
}}

Essentially I need help with figuring out then the Text Editor is tapped out of.

This is the design of it for reference: Text Editor

  • sorry, but I just don't understand your question here. Could you explain a bit more, what you want. – workingdog support Ukraine Jul 20 '21 at 07:57
  • Sorry for the unclarity, when you tap on the text editor I want the label to float up and when you tap out or on another element for the label to return to its original position. Hope this makes it a bit more clear – Filip Jurković Jul 20 '21 at 08:03

1 Answers1

0

Looks like you are already handling when it gets clicked originally, just failing to handle when it loses focus. You need to use something like onCommit as well as onTapGesture.

Ian
  • 35
  • 5