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

SwiftUI滚动视图选中项样式修改:字号与粗体设置需求

解决方案

关键修改点:

  • 修复状态变量位置:@State变量必须定义在结构体顶层(body是计算属性,不能在内部声明状态)
  • 添加字体加粗逻辑:通过Font.system的weight参数,为选中项设置加粗样式
  • 确保Filter可识别:Filter结构体需要遵循Identifiable协议(或拥有唯一id属性),保证ForEach正常工作

修正后的完整代码:

struct Filter: Identifiable {
    let id = UUID()
    let name: String
}

struct UserFeedView: View {
    // 将@State移到结构体顶层
    @State private var selectedFilter: Filter?
    
    let filters = [
        Filter(name: "All"),
        Filter(name: "fil1"),
        Filter(name: "fil2"),
        Filter(name: "fil3"),
    ]

    var body: some View {
        VStack() {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 15) {
                    ForEach(filters) { filter in
                        Text(filter.name)
                            // 同时设置字号和字重:选中项更大+加粗,未选中常规字号+普通字重
                            .font(.system(
                                size: selectedFilter?.id == filter.id ? 30 : 20,
                                weight: selectedFilter?.id == filter.id ? .bold : .regular
                            ))
                            .onTapGesture {
                                selectedFilter = filter
                            }
                    }
                }
                .padding(.top, 10)
                .padding(.leading, 30)
            }
            .frame(height: 150)
            .onAppear {
                // 默认选中第一个选项
                selectedFilter = filters.first
            }
            Spacer()
        }
    }
}

说明:

  • 选中的Filter文本会同时应用更大字号(30)和加粗字重,未选中项使用常规字号(20)和普通字重,视觉差异清晰
  • Filter结构体添加了Identifiable协议的默认实现(通过UUID()生成唯一id),如果你的Filter已有自定义id,可以保留自己的实现
  • 页面加载时自动选中第一个Filter,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:12:23