RapsIn4
RapsIn4

Reputation: 91

How to stop divider from disappearing when I input text into TextField using keyboard

I'm working on a Login View and I have two Dividers(), one that underlines the Username TextField and another one that underlines the Password TextField. Using a physical device for simulation, when I try to enter in Text into the Username Field, the divider underneath it's TextField disappears and then reappears when I dismiss the keyboard, however this doesn't happen with the Password Divider.

Also, this behavior does not occur if I remove the Image View that's on top of the TextField. Any suggestions on why this happens and how I can go about fixing this?

Much appreciated!

VStack{

    Image(uiImage: #imageLiteral(resourceName: "awText"))
        .resizable()
        .frame(width: 180, height: 100)
        .padding(.bottom, 50)
    
    TextField("Username", text: $username)
        .padding(.leading)
    Divider()
        .padding(.bottom)
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10)) //Max 10 Characters for Username.
            }
        })
        .disableAutocorrection(true)
    
    SecureField("Password", text: $password)
        .padding(.leading)
    Divider()
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10)) //Max 10 Characters for Password.
            }
        })
        .disableAutocorrection(true)

}

Upvotes: 1

Views: 348

Answers (1)

swiftPunk
swiftPunk

Reputation: 1

Try this codes with Rectangle!


struct ContentView: View {
    
    @State private var username: String = String()
    @State private var password: String = String()

    var body: some View {
        
        VStack{
            Image(systemName: "star")
                .resizable()
                .frame(width: 180, height: 100)
                .padding(.bottom, 50)
            
            TextField("Username", text: $username)
                .padding(.leading)
            
            Rectangle().fill(Color.gray.opacity(0.25)).frame(height: 1, alignment: .center).padding(.bottom)
                
   
            SecureField("Password", text: $password)
                .padding(.leading)
            
            Rectangle().fill(Color.gray.opacity(0.25)).frame(height: 1, alignment: .center)

        }
        .disableAutocorrection(true)
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10))
            }
        })
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10))
            }
        })
        
        
    }

}

Upvotes: 1

Related Questions