Swiftui Scrollview 文本改变颜色 onTapGesture
Swiftui Scrollview text change color onTapGesture
我想在 onTapGesture 上更改文本项的颜色以模拟所选项目,单击时文本颜色应为红色,其他文本为黑色。
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(newsFeed.subcategoryListNews) { item in
Text(item.name)
.font(Font.custom("AvenirNextLTPro-Demi", size: 17))
.foregroundColor(Color.black)
.onTapGesture {
//Chage color and reset other Text, active red not active black
}
}
}
.padding(.top, 30)
.padding(.horizontal, 30)
}.padding(.bottom, 10)
非常感谢
它需要符合你的项目类型Equatable
(如果还没有)那么下面的方法是可能的
@State private var selectedItem: <Item_Type_Here>? = nil
...
ForEach(newsFeed.subcategoryListNews) { item in
Text(item.name)
.font(Font.custom("AvenirNextLTPro-Demi", size: 17))
.foregroundColor(self.selectedItem == item ? Color.red : Color.black))
.onTapGesture {
self.selectedItem = item
}
}
我想在 onTapGesture 上更改文本项的颜色以模拟所选项目,单击时文本颜色应为红色,其他文本为黑色。
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(newsFeed.subcategoryListNews) { item in
Text(item.name)
.font(Font.custom("AvenirNextLTPro-Demi", size: 17))
.foregroundColor(Color.black)
.onTapGesture {
//Chage color and reset other Text, active red not active black
}
}
}
.padding(.top, 30)
.padding(.horizontal, 30)
}.padding(.bottom, 10)
非常感谢
它需要符合你的项目类型Equatable
(如果还没有)那么下面的方法是可能的
@State private var selectedItem: <Item_Type_Here>? = nil
...
ForEach(newsFeed.subcategoryListNews) { item in
Text(item.name)
.font(Font.custom("AvenirNextLTPro-Demi", size: 17))
.foregroundColor(self.selectedItem == item ? Color.red : Color.black))
.onTapGesture {
self.selectedItem = item
}
}