Erik
Erik

Reputation: 519

How to change size of field in TextField?

I need to change the size (actually just the height) of the TextField. Using .padding() increases just the area around the TextField, but not the field itself. I've tried some possible solutions:

  1. Change the font size: This approach works, but I don't want to have a TextField with a too large text in itself.

  2. Using custom modifier doesn't work. I get the message Inheritance from non-protocol type 'TextFieldStyle'. Seems to not working in Swift 5 anymore?

My current solution is:

@State private var searchText: String = ""

var body: some View {

HStack{
    Image(systemName: "magnifyingglass")
        .font(.system(size: 20, weight: .bold))
    
    ZStack(alignment: .leading){
        if searchText.isEmpty { Text("search") }
        TextField("", text: $searchText,
                  onEditingChanged: { focused in
                    if focused {
                        // do something...
                    }
                  },
                  onCommit: {
                    // do something...
                  })
            .keyboardType(.alphabet)
            .disableAutocorrection(true)
            .frame(height: 50)
    }
    .textFieldStyle(PlainTextFieldStyle())
}
.frame(height: 30)
.frame(maxWidth: .infinity)
.foregroundColor(.white)
.accentColor(.white)
.padding()
.background(
    Color("Color-2")
        .cornerRadius(20)
        .shadow(color: Color.black.opacity(0.3), radius: 5, x: 5, y: 5)
)
.contentShape(Rectangle())
}}

Only the red area is "clickable"

enter image description here

Upvotes: 2

Views: 3413

Answers (1)

swiftPunk
swiftPunk

Reputation: 1

import SwiftUI

struct ContentView: View {
    
    @State var stringOfText: String = ""
    
    var body: some View {

        TextField("", text: $stringOfText)
            .font(Font.system(size: 50))
            .background(Color.yellow)
            .foregroundColor(Color.clear)
            .cornerRadius(10)
            .overlay(Text(stringOfText), alignment: .leading)
            .padding()
            .shadow(radius: 10)

    }
}

Upvotes: 3

Related Questions