在SwiftUI中,如何在点击时更改按钮的背景颜色

18

我正在尝试在SwiftUI中更改Button的颜色。这是我的整个CustomButton视图结构:

我试图在SwiftUI中更改Button的颜色。这是我的整个CustomButton视图结构:

struct CustomButton: View {

    @State private var didTap:Bool = false

    var body: some View {
        Button(action: {
            self.didTap = true
        }) {

        Text("My custom button")
            .font(.system(size: 24))
        }
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(Color.yellow)

        //My code above this comment works fine

        //I tried something like this, but it is not working
     //   if didTap == true {
     //   .background(Color.blue)
     //    }

    }
}

这是我的按钮外观(很好):

My custom button

但我的问题是:当用户点击此按钮时,如何更改背景颜色。

谢谢。

4个回答

23
为了做到这一点,您需要根据状态进行颜色设置:
struct CustomButton: View {

@State private var didTap:Bool = false

  var body: some View {
    Button(action: {
        self.didTap = true
    }) {

    Text("My custom button")
        .font(.system(size: 24))
    }
    .frame(width: 300, height: 75, alignment: .center)
    .padding(.all, 20)
    .background(didTap ? Color.blue : Color.yellow)
  }
}

注意: 如果您还想管理其他状态,那么可以使用enum


1
有没有办法在点击之后将颜色重置回去? - pizzae
1
使用 self.didTap.toggle() 替代 self.didTap = true,这样每次点击后它就会来回切换。@pizzae - jwknz
@jwknz 这是否意味着您必须再次轻触它,即总共轻触2次才能返回原始颜色?有没有办法使其在单次轻触后立即改变颜色? - pizzae
@pizzae 嗯,除非你将该颜色设置为false的值,否则它不会改回原来的颜色 - 那么是的,需要2次点击。如果您想在一段时间后将其更改回来,则可以使用计时器,并在一定秒数或任何您想要实现的时间后将其设置回来。 - jwknz

7

万一有人想用另一种方法来完成这个任务,我可以提供一个更为通用的解决方案。它可以适用于更多的颜色。

struct CustomButton: View {

    @State private var buttonBackColor:Color = .yellow

    var body: some View {
        Button(action: {

            //This changes colors to three different colors.
            //Just in case you wanted more than two colors.
             if (self.buttonBackColor == .yellow) {
                 self.buttonBackColor = .blue
             } else if self.buttonBackColor == .blue {
                 self.buttonBackColor = .green
             } else {
                 self.buttonBackColor = .yellow
             }

            //Same code using switch
            /*
             switch self.buttonBackColor {
             case .yellow:
                 self.buttonBackColor = .blue
             case .blue:
                 self.buttonBackColor = .green
             default:
                 self.buttonBackColor = .yellow
             }
             */
        }) {

        Text("My custom button")
            .font(.system(size: 24))
        }
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(buttonBackColor)
    }
}

0

这是一段时间前基于制作问答应用程序所做的。如果用户回答正确,按钮会变成绿色,如果回答错误,则变成红色。同样,通过删除elif语句,也可以将其应用于可点击的按钮。

    @IBAction func answerButtonPressed(_ sender: UIButton) {
    
    
    let actualAnswer = quiz[questionNumber].a
    let buttonPressed = sender.currentTitle!

    
    if buttonPressed == actualAnswer {
        print("Right")
        sender.backgroundColor = UIColor.green
    } else {
        print("wrong")
        sender.backgroundColor = UIColor.red
    }

0

但在新的方式中,或者在新版本的Swift、Xcode和iOS中,你只需要写.color_name,如果你使用类似上面的class,那么它会生成错误。

在Struct类中,只需添加ContentView: View

@State private var didTap:Bool = false

Button(action:{
    self.didTap = true
}) {
    Text("ಕನ್ನಡ").font(.system(size: 17))
        .fontWeight(.bold)
        .foregroundColor(didTap ? .orange :.black)
        .frame(minWidth: 0, maxWidth:143)
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 10)
                .fill(Color.white)
                .shadow(color: .gray, radius: 2, x: 0, y: 2)
        )
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接