swiftui - @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[]
?
解决方案
我假设您打算在点击时更改选择,可以按如下方式完成
VStack(spacing: 8) {
Text(topMenu[menu])
.font(.system(size: 15))
.fontWeight(index == menu ? .bold : .none)
.foregroundColor(index == menu ? .black : .gray)
.onTapGesture {
index = menu // << here !!
}
推荐阅读
- python-3.x - 我如何使用 selenium 自动处理本网站上的特定问题?我基本上必须搜索一些东西,它类似于多项选择
- angular - 在现有项目中创建 Angular Web 组件
- python - gspread - 按列名获取特定列
- .net-core - 在 Entity Framework Core 中使用自定义链接表时的派生列
- c# - 切换语言设置时 jwt 令牌结果过期
- android - public final fun actionFragmentAToDetailActivity() 的参数太多
- python - 基于相同的列名加入多个 Pyspark 数据框
- c++ - 为什么我的 C++ DLL 不适用于我的 Delphi 应用程序?
- javascript - 获取 Firestore 图片 url 并显示在图片标签中
- java - 如何在 TableRow 创建期间让 FileChooser 填充 TextView?