简体   繁体   English

按下按钮后如何更改 SwiftUI 中的按钮

[英]How do I change a button in SwiftUI after a button is pressed

I want a card image to change to another card image when I press a button.当我按下按钮时,我希望一张卡片图像变为另一张卡片图像。 This is my current code:这是我当前的代码:

import SwiftUI

var leftCard = "green_back"
var rightCard = "blue_back"

func dealCards() {
    leftCard = "1C"
    print("deal")
}

struct GameView: View {
    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 20) {
                Image(leftCard)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    
                Image(rightCard)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
            .padding(.all, 25)
            
            Button(action: dealCards) {
                Text("Deal Cards")
                    .fontWeight(.bold)
                    .font(.title)
                    .padding(10)
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .padding(10)
                    .border(Color.blue, width: 5)
            }
        }
    }
}

struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView()
    }
}

This code prints "deal" when I press the button, but it doesn't change the image.当我按下按钮时,此代码会打印“交易”,但不会更改图像。

I am using MacOS Big Sur beta 3 and Xcode 12 beta 2.我正在使用 MacOS Big Sur beta 3 和 Xcode 12 beta 2。

Edit: I just had to move my variables into the GameView struct and add a @State modifier to them.编辑:我只需将变量移动到 GameView 结构中并向它们添加@State修饰符。 Thanks to everyone who answered.感谢所有回答的人。 :D :D

You can even remove the function and add the code directly to button您甚至可以删除 function 并将代码直接添加到按钮

struct GameView: View {
    
    @State var leftCard = "green_back"
    @State var rightCard = "blue_back"
    
    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 20) {
                Image(leftCard)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                
                Image(rightCard)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
            .padding(.all, 25)
            
            Button(action: {
                self.leftCard = "1C"
            }) {
                
                Text("Deal Cards")
                    .fontWeight(.bold)
                    .font(.title)
                    .padding(10)
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .padding(10)
                    .border(Color.blue, width: 5)
            }
        }
    }
}

The following code should update your Images and should give you a random value as well in the deal() function.以下代码应更新您的Images ,并应在deal() function 中为您提供一个随机值。

It is very important that you define your properties and functions inside a View or component.View或组件中定义属性和函数非常重要。 Global variables are generally not recommended and can lead to unexpected results.全局变量一般不推荐使用,可能会导致意想不到的结果。

import SwiftUI

struct GameView: View {

    // 1. Add ImageName to handle names via dot (.) to avoid mistyping strings. CaseIterable allow you to get an array of all the values defined.
    enum ImageName: String, CaseIterable {
        case greenBack = "green_back"
        case blueBack = "blue_back"
        case other = "1C"
    }

    // 2. Add @State to update the GameView() automatically when any of the properties are updated.
    @State private var leftCard: ImageName = .greenBack
    @State private var rightCard: ImageName = .blueBack

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 20) {

                // 3. Add .rawValue to get the raw String value
                Image(leftCard.rawValue)
                    .resizable()
                    .aspectRatio(contentMode: .fit)

                Image(rightCard.rawValue)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
            .padding(.all, 25)

            Button(action: dealCards) {
                Text("Deal Cards")
                    .fontWeight(.bold)
                    .font(.title)
                    .padding(10)
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .padding(10)
                    .border(Color.blue, width: 5)
            }
        }
    }

    func dealCards() {
        // 4. Update the name via dot(.) of any card that you want.
        // You can also randomise the card doing .allCases.randomElement()
        leftCard = ImageName.allCases.randomElement() ?? .greenBack
        print("deal")
    }
}

struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView()
    }
}

You can move your variables to the GameView and add @State modifier:您可以将变量移动到GameView并添加@State修饰符:

struct GameView: View {
    @State var leftCard = "green_back"
    @State var rightCard = "blue_back"
    
    var body: some View {
        ...
    }
    
    func dealCards() {
        leftCard = "1C"
        print("deal")
    }
}

This way SwiftUI will refresh the view when your @State variables change.这样 SwiftUI 将在您的@State变量更改时刷新视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在swiftui中按下按钮时更改按钮图像 - How to change a button image when the button is pressed in swiftui 如何在收藏后更改并保留按钮颜色,然后在 SwiftUI 中切换回来? - How do I change and persist the button color after favoriting and then switch back in SwiftUI? 在 SwiftUI 中按下按钮时更改视图 - Change the view when a button is pressed in SwiftUI 按下时如何为 swiftUI 按钮提供多种功能? - How can I give a swiftUI button multiple functions when pressed? 未按下按钮时如何调用按钮功能 - How do I call a button function when the button is not being pressed 在 SwiftUI 中,如何增加按钮的高度? - In SwiftUI, How do I increase the height of a button? 我如何设置标签,以便在按下按钮时它将更改标签上显示的值 - How do i set up a label so that when a button is pressed then it will change that value displayed on the label 只要按下键盘上的x按钮,如何从一个文本字段中删除另一个文本字段中的值 - How do I delete value from one textfield after the other as long as x button on keyboard is pressed XCODE SWIFT 如何在按下按钮后执行代码,但在另一个文件/类中? - XCODE SWIFT How do I execute code after a button is pressed, but in another file/class? 保存按下按钮的值(SwiftUI) - Save the value of the pressed button (SwiftUI)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM