我如何在swiftUI视图中使用按钮? [关闭]

问题描述 投票:0回答:1

如何在swiftUI视图中使用按钮?该视图将仅包含按钮和一些文本。轻按按钮时,它将执行一个功能,该功能将更改文本中的单词,然后等待再次点击按钮并重复。我可以很容易地使用UIKit做到这一点,但是使用swiftUI,Button似乎比我预期的参与得多。

button swiftui
1个回答
1
投票

因此,您可以通过创建自定义按钮来在许多视图中使用该方法。

/// 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()
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.