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

如何用Swift UI创建类似Material UI带标签的文本输入框?

SwiftUI实现Material UI风格的圆角输入框

直接给你一个可复用的自定义组件,完美实现你要的效果——标签默认在输入框内,聚焦或输入内容后自动缩到边框上方,同时支持圆角边框:

import SwiftUI

struct MaterialTextField: View {
    let label: String
    @Binding var text: String
    @FocusState private var isFocused: Bool
    
    private var isLabelFloating: Bool {
        !text.isEmpty || isFocused
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(label)
                .font(isLabelFloating ? .caption : .body)
                .foregroundColor(isLabelFloating ? .blue : .gray)
                .offset(y: isLabelFloating ? -24 : 0)
                .animation(.easeInOut(duration: 0.2), value: isLabelFloating)
            
            TextField("", text: $text)
                .focused($isFocused)
                .padding(12)
                .background(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(isFocused ? .blue : .gray, lineWidth: 1)
                )
        }
        .padding(.top, isLabelFloating ? 8 : 0)
    }
}

// 使用示例
struct ContentView: View {
    @State private var email = ""
    @State private var password = ""
    
    var body: some View {
        VStack(spacing: 24) {
            MaterialTextField(label: "邮箱", text: $email)
            MaterialTextField(label: "密码", text: $password)
        }
        .padding(20)
    }
}

关键实现细节:

  • 用@FocusState监听输入框聚焦状态,结合文本是否为空判断标签是否需要"上浮"
  • 通过offset调整标签位置,配合动画实现平滑过渡效果
  • 自定义圆角边框:用RoundedRectangle作为背景,根据聚焦状态切换边框颜色
  • 标签的字体大小和颜色随状态动态变化,完全贴合Material UI的交互逻辑

你可以根据Figma设计,自行调整圆角半径(cornerRadius)、边框色值、字体样式这些参数。

内容的提问来源于stack exchange,提问作者Daniel Lopes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:32:45