swiftui - SwiftUI:有一个按钮自己改变吗?
问题描述
我正在尝试制作一个显示单选按钮菜单的结构。
我遇到的问题如下:当我按下按钮时,我希望 Text(item) View 改变颜色。我不知道该怎么做,因为 Text(item) 包含在按钮中。
import SwiftUI
struct RadioMenu: View {
var items = [String]()
@State var isChecked: Bool = false
@State var selection: String? = nil
var textSize: Int = 20
init(items: [String], textSize: Int) {
self.items = items
self.textSize = textSize
}
var body: some View {
VStack {
ForEach(items, id:\.self) { item in
Button (action: {
self.isChecked = true
self.selection = item
}) {
Text(item)
.font(.system(size: CGFloat(self.textSize), weight: .medium, design: .rounded))
.padding()
.overlay(
RoundedRectangle(cornerRadius: 15)
.stroke(lineWidth: 2)
)}
.padding(.bottom, 10)
}
}
}
}
解决方案
您可以将此修饰符应用于Text
:
.foregroundColor(item == self.selection ? Color.red : Color.black)
推荐阅读
- azure - 使用 Azure Logic App 和 Azure Function 更改数据库时使 redis 缓存失效
- javascript - ActionController::RoutingError (没有路由匹配 [GET] )
- javascript - 如何使用 if else 条件在其他 div 之后插入 div
- printing - 如何在 SAP 上安装 .PRI 打印机定义?
- node.js - 如何在对象数组中查找和过滤mongo?
- terminal - Composer 无法安装 yii2 扩展
- regex - 相对 URL 的正则表达式(域名后的段)[& 没有查询字符串]
- javascript - 使用“onClick={}”被认为是一种不好的做法吗?
- javascript - 科学记数法到十进制记数法在 highcharts 中不起作用
- node.js - 将 mongo 嵌套数组查询翻译成 mongoose