SwiftUI:调整TextField尺寸并实现文本左上对齐的方法
SwiftUI TextField 文本顶部对齐解决方案
你的问题出在TextField的frame默认垂直对齐为居中,导致高度扩展时文本停留在中间位置。只需调整frame的对齐方式,并可优化聚焦状态的逻辑来简化代码:
修改点1:设置frame的顶部对齐
将TextField的frame修饰符添加alignment: .topLeading参数,让文本在容器内左上对齐:
.frame(width: textFieldWidth, height: textFieldHeight, alignment: .topLeading)
修改点2:优化聚焦状态逻辑(可选)
原代码中用两个TapGesture切换高度的方式容易出现冲突,建议直接利用FocusState的变化控制高度,更准确可靠:
- 移除原来的两个
gesture和simultaneousGesture修饰符 - 添加
onChange监听聚焦状态:
.onChange(of: focusCursorVisible) { isFocused in withAnimation { textFieldHeight = isFocused ? 100 : 30 } }
修改后的完整代码
struct MemInputFieldView: View { @EnvironmentObject var globalStyles: GlobalStyles @State private var memText: String = "" @State private var textFieldWidth: CGFloat = .infinity @State private var textFieldHeight: CGFloat = 30 @FocusState private var focusCursorVisible: Bool var body: some View { VStack() { TextField("Type here...", text: $memText, axis: .vertical) .focused($focusCursorVisible) .frame(width: textFieldWidth, height: textFieldHeight, alignment: .topLeading) .padding(globalStyles.defaultPadding + 4) .font(.headline) .background(Color(UIColor.systemGray6)) .textInputAutocapitalization(.never) .disableAutocorrection(true) .cornerRadius(6) .padding(globalStyles.defaultPadding) .multilineTextAlignment(.leading) .onChange(of: focusCursorVisible) { isFocused in withAnimation { textFieldHeight = isFocused ? 100 : 30 } } Separator() } } }
这样修改后,TextField高度扩展时文本会保持在顶部位置,同时聚焦逻辑更简洁,避免手势冲突问题。
内容的提问来源于stack exchange,提问作者NorseGaud
相关产品推荐
相关产品推荐

