Button 如何在swiftUI视图中使用按钮?

Button 如何在swiftUI视图中使用按钮?,button,swiftui,Button,Swiftui,如何在swiftUI视图中使用按钮?视图将只包含按钮和一些文本。当点击按钮时,它将执行一个功能,该功能将更改文本中的文字,然后等待再次点击按钮并重复。我可以用UIKit轻松地完成这项工作,但使用swiftUI时,按钮似乎比我预期的要复杂得多。因此,您可以这样做,即创建一个可在许多视图上使用的自定义按钮 /// Custom button that can be used in any view struct CustomButton: View { // This is the custo

如何在swiftUI视图中使用按钮?视图将只包含按钮和一些文本。当点击按钮时,它将执行一个功能,该功能将更改文本中的文字,然后等待再次点击按钮并重复。我可以用UIKit轻松地完成这项工作,但使用swiftUI时,按钮似乎比我预期的要复杂得多。

因此,您可以这样做,即创建一个可在许多视图上使用的自定义按钮

/// Custom button that can be used in any view
struct CustomButton: View {

  // This is the custom method called from other views
  var action: () -> ()

  var body: some View {
    VStack {
      Button(action: { self.action() }) {
        Text("Tap me")
      }
    }
  }
}
然后,您可以在主视图中以这种方式使用它,例如更改文本。您可以在changeMyText方法中添加任何需要的内容

// Your main view
struct ContentView: View {

  // Keep track of the change of a tap
  @State private var buttonTapped = false

  var body: some View {
    VStack(spacing: 50) {

      Text(buttonTapped ? "My second Text" : "My first text")

      // Declare your custom button with desired functions
      CustomButton(action: { self.changeMytext() })
    }
  }

  // Method where you perform whatever you need
  func changeMytext() {
    self.buttonTapped.toggle()
  }
}

在本例中,是什么导致点击按钮后重新显示ContentView?我希望看到类似于UIKit的“setNeedsDisplay”的东西,但我没有看到。ContentView是否会触发显示任何更改?ContentView是一个结构,因此是静态的。触发视图更改的对象是@State。每次“@State”值更改时,视图本身都会重新计算应显示的更改,并使用新更改重写自身。这与UIKit相比有很大的不同,这就是为什么在SwiftUI中不再需要ViewController的原因。