You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI:调整TextField尺寸并实现文本左上对齐的方法

SwiftUI TextField 文本顶部对齐解决方案

你的问题出在TextField的frame默认垂直对齐为居中,导致高度扩展时文本停留在中间位置。只需调整frame的对齐方式,并可优化聚焦状态的逻辑来简化代码:

修改点1:设置frame的顶部对齐

将TextField的frame修饰符添加alignment: .topLeading参数,让文本在容器内左上对齐:

.frame(width: textFieldWidth, height: textFieldHeight, alignment: .topLeading)

修改点2:优化聚焦状态逻辑(可选)

原代码中用两个TapGesture切换高度的方式容易出现冲突,建议直接利用FocusState的变化控制高度,更准确可靠:

  1. 移除原来的两个gesture和simultaneousGesture修饰符
  2. 添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:23:35