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

如何在SwiftUI中实现Figma设计的双侧切换按钮?

实现SwiftUI双侧切换按钮(带选中下划线)

直接上可运行的实现代码,完全匹配你描述的Figma设计:

import SwiftUI

struct TabToggleView: View {
    // 用枚举管理选中状态,比字符串更安全
    enum SelectedTab {
        case lyrics, chords
    }
    
    @State private var selectedTab: SelectedTab = .lyrics
    
    var body: some View {
        HStack(spacing: 0) {
            // Lyrics按钮
            Button(action: {
                selectedTab = .lyrics
            }) {
                VStack(spacing: 4) {
                    Text("Lyrics")
                        .font(.headline)
                        .foregroundColor(selectedTab == .lyrics ? .blue : .gray)
                    // 选中状态显示的下划线
                    Rectangle()
                        .frame(height: 2)
                        .foregroundColor(.blue)
                        .opacity(selectedTab == .lyrics ? 1 : 0)
                }
            }
            .frame(maxWidth: .infinity)
            
            // Chords按钮
            Button(action: {
                selectedTab = .chords
            }) {
                VStack(spacing: 4) {
                    Text("Chords")
                        .font(.headline)
                        .foregroundColor(selectedTab == .chords ? .blue : .gray)
                    Rectangle()
                        .frame(height: 2)
                        .foregroundColor(.blue)
                        .opacity(selectedTab == .chords ? 1 : 0)
                }
            }
            .frame(maxWidth: .infinity)
        }
        .padding(.vertical, 8)
        .background(Color(.systemGray6))
        .cornerRadius(8)
    }
}

// 预览
struct TabToggleView_Previews: PreviewProvider {
    static var previews: some View {
        TabToggleView()
            .padding()
    }
}

关键实现细节说明:

  • 用@State变量selectedTab追踪当前选中项,确保UI实时响应状态变化
  • 每个按钮用VStack包裹文字和下划线,通过opacity控制下划线的显示/隐藏(也可以用hidden(),但opacity过渡更平滑)
  • 两个按钮都设置frame(maxWidth: .infinity),保证它们平分父容器的宽度,实现对称布局
  • 可根据Figma设计灵活调整:
    • 下划线高度(frame(height: 2))
    • 文字字体、颜色
    • 按钮背景色、圆角
    • 文字与下划线的间距(VStack(spacing: 4))

如果需要平滑过渡动画,给下划线添加.animation(.easeInOut(duration: 0.2), value: selectedTab)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:24:59