如何在视图上创建扩展以显示长按手势的警报 - SwiftUI
How to create an extension on a view to show alerts on long press gesture - SwiftUI
我正在 iOS 13 在 Xcode 11.6
中在 SwiftUI 中创建一个应用程序
我想在 SwiftUI 的视图上创建一个扩展,当用户长按视图时显示警告消息。
例如,假设我有这样一个视图:
import SwiftUI
struct TestView: View {
var body: some View {
TabView {
Text("1").addLongPressAlert("Test 1")
Text("2").addLongPressAlert("Test 2")
Text("3").addLongPressAlert("Test 3")
}
}
}
View 上的扩展看起来像这样:
extension View {
public func addLongPressAlert(message _ : String) -> some View {
return self.onLongPressGesture {
// I know this is not how you show an alert, but im unsure how to display it
Alert(title: Text("Alert"), message: Text(m), dismissButton: .default(Text("OK!")))
}
}
}
我正在努力弄清楚如何正确设置它。
有人知道如何实现吗?
您可以创建自定义 ViewModifier
:
struct LongPressAlertModifier: ViewModifier {
@State var showAlert = false
let message: String
func body(content: Content) -> some View {
content
.onLongPressGesture {
self.showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Alert"), message: Text(message), dismissButton: .default(Text("OK!")))
}
}
}
并像这样使用它:
Text("1").modifier(LongPressAlertModifier(message: "Test1"))
您甚至可以创建自定义 View
扩展:
extension View {
func addLongPressAlert(_ message: String) -> some View {
self.modifier(LongPressAlertModifier(message: message))
}
}
并以更方便的方式使用修饰符:
Text("1").addLongPressAlert("Test 1")
我正在 iOS 13 在 Xcode 11.6
中在 SwiftUI 中创建一个应用程序我想在 SwiftUI 的视图上创建一个扩展,当用户长按视图时显示警告消息。
例如,假设我有这样一个视图:
import SwiftUI
struct TestView: View {
var body: some View {
TabView {
Text("1").addLongPressAlert("Test 1")
Text("2").addLongPressAlert("Test 2")
Text("3").addLongPressAlert("Test 3")
}
}
}
View 上的扩展看起来像这样:
extension View {
public func addLongPressAlert(message _ : String) -> some View {
return self.onLongPressGesture {
// I know this is not how you show an alert, but im unsure how to display it
Alert(title: Text("Alert"), message: Text(m), dismissButton: .default(Text("OK!")))
}
}
}
我正在努力弄清楚如何正确设置它。
有人知道如何实现吗?
您可以创建自定义 ViewModifier
:
struct LongPressAlertModifier: ViewModifier {
@State var showAlert = false
let message: String
func body(content: Content) -> some View {
content
.onLongPressGesture {
self.showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Alert"), message: Text(message), dismissButton: .default(Text("OK!")))
}
}
}
并像这样使用它:
Text("1").modifier(LongPressAlertModifier(message: "Test1"))
您甚至可以创建自定义 View
扩展:
extension View {
func addLongPressAlert(_ message: String) -> some View {
self.modifier(LongPressAlertModifier(message: message))
}
}
并以更方便的方式使用修饰符:
Text("1").addLongPressAlert("Test 1")