Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change size of field in TextField?

Tags:

swiftui

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

like image 466
Erik Avatar asked Dec 20 '25 09:12

Erik


1 Answers

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)

    }
}
like image 65
ios coder Avatar answered Dec 22 '25 00:12

ios coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!