首页 > 解决方案 > 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)
            }
        }

    }
}

标签: swiftui

解决方案


您可以将此修饰符应用于Text

.foregroundColor(item == self.selection ? Color.red : Color.black)

推荐阅读