如何在SwiftUI中创建带指定背景色和白色下划线的自定义TextField?
在SwiftUI中创建带自定义背景和白色下划线的TextField
你的原代码存在视图重叠(用ZStack堆叠所有元素)、TextField样式不符合需求、数据绑定错误等问题,以下是修复并实现目标效果的方案:
我们通过自定义TextFieldStyle来实现背景色+白色下划线的效果,同时重构布局让界面结构更清晰:
import SwiftUI @available(iOS 16.0, *) struct SecondView: View { @State private var nome = "" @State private var cognome = "" var body: some View { ZStack { // 全局背景色 Color(red: 57/255, green: 63/255, blue: 147/255) .ignoresSafeArea() VStack(spacing: 20) { Text("Ora tocca ai tuoi dati") .font(.custom("Rubik", size: 22).weight(.light)) .foregroundColor(.white) Text("Per iniziare ad usare MyEntZo completa i campi qui sotto") .font(.custom("Rubik", size: 18).weight(.light)) .foregroundColor(.white) .multilineTextAlignment(.center) .padding(.horizontal, 20) // 自定义样式的姓名输入框 TextField("Nome", text: $nome) .textFieldStyle(CustomTextFieldStyle()) .foregroundColor(.white) // 自定义样式的姓氏输入框(修复原绑定错误) TextField("Cognome", text: $cognome) .textFieldStyle(CustomTextFieldStyle()) .foregroundColor(.white) Spacer() Button(action: { print("sign up bin tapped") }) { Text("Continua") .frame(maxWidth: .infinity) .font(.system(size: 18)) .padding() .foregroundColor(.white) .background(Color.green) .cornerRadius(25) .overlay( RoundedRectangle(cornerRadius: 25) .stroke(Color.green, lineWidth: 2) ) } .padding(.horizontal, 25) } .padding(.top, 40) } } } // 自定义TextField样式:实现背景色+白色下划线 struct CustomTextFieldStyle: TextFieldStyle { func _body(configuration: TextField<Self._Label>) -> some View { VStack(alignment: .leading, spacing: 0) { configuration .padding(.vertical, 12) .padding(.horizontal, 16) // 可根据需求调整背景色 .background(Color(red: 45/255, green: 50/255, blue: 120/255)) // 底部白色下划线 Rectangle() .fill(.white) .frame(height: 1) .padding(.horizontal, 16) } } } struct SecondView_Previews: PreviewProvider { static var previews: some View { SecondView() } }
关键修改说明
- 布局重构:用VStack替代ZStack,让视图垂直有序排列,避免元素重叠,同时通过Spacer将按钮推至底部,布局更合理。
- 自定义TextField样式:
CustomTextFieldStyle封装了背景色和白色下划线逻辑,可直接复用,背景色的RGB值可根据实际需求调整。 - 修复数据绑定:原代码中第二个TextField错误绑定了
$nome,现已修正为$cognome,保证数据逻辑正确。 - 简化样式代码:合并了重复的字体设置,让代码更简洁易维护。
内容的提问来源于stack exchange,提问作者riki
相关产品推荐
相关产品推荐

