我想用一个按钮和一些文本制作一个swiftUI视图。当点击按钮时,它将执行一个功能,该功能将更改某些文本中的单词,然后等待另一次点击并重复。我可以使用UIKit轻松地完成此操作,但是使用swiftUI时,Button显然比我预期的要复杂得多。有人可以给我指出一个带有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 view with desired function
CustomButton(action: { self.changeMytext() })
}
}
// Method where you perform whatener you need
func changeMytext() {
self.buttonTapped.toggle()
}
}