首页 > 解决方案 > @State 变量以突出显示水平 ScrollView 菜单中的项目

问题描述

我正在练习一个应用程序,其中菜单的一部分是一个水平滚动列表,一个小圆圈应该突出显示当前选择。代码如下:

import SwiftUI
        
        struct ContentView: View {
            @State var index = 0
            
            var body: some View {
                
                ScrollView(.horizontal, showsIndicators:false) {
                HStack(spacing: 30) {
                    
                ForEach(0..<topMenu.count, id: \.self){ menu in
                    TopMenu(menu: menu, index: $index)
                        }
                    }
            }
                }  
        }
        
       var topMenu = ["Shoes", "Clothing", "By Sports", "By Brand", "By Price"]
        
        struct TopMenu: View {
            var menu: Int
            @Binding var index: Int
            
            var body: some View {
                
                VStack(spacing: 8) {
                       Text(topMenu[menu])
                         .font(.system(size: 15))
                         .fontWeight(index == menu ? .bold : .none)
                         .foregroundColor(index == menu ? .black : .gray)
                     Circle()
                         .fill(Color.black)
                         .frame(width: 10, height: 10)
                         .opacity(index == menu ? 1 : 0)
                 }
            }
        }
        
        struct ContentView_Previews: PreviewProvider {
            static var previews: some View {
                ContentView()
            }
        }

但是现在这一切似乎都非常静态,我似乎无法弄清楚如何更改@Binding变量的值,以便它显示当前选择的项目topMenu[]

临时输出供参考

标签: swiftui

解决方案


我假设您打算在点击时更改选择,可以按如下方式完成

 VStack(spacing: 8) {
          Text(topMenu[menu])
             .font(.system(size: 15))
             .fontWeight(index == menu ? .bold : .none)
             .foregroundColor(index == menu ? .black : .gray)
             .onTapGesture {
                index = menu     // << here !!
            }

推荐阅读