我是 swiftui 的初学者,我正在尝试在 swiftui 中构建属性类型文本。我能够这样做,现在对于链接而不是 url,我需要有一个自定义弹出窗口,所以我试图将点击操作从文本传递到我的主视图,但它不起作用,下面是我的代码。
struct ContentText: View {
private var splitText: [String]
let count: Int
var type: ViewType
@State var handler: ((String) -> Void) = {_ in}
init(_ text: String, type: ViewType = .text) {
self.splitText = text.split(separator: " ").map { "\($0) " }
if text.hasPrefix(" ") {
self.splitText = [" "] + self.splitText
}
self.type = type
self.count = splitText.count
}
var body: some View {
ForEach(self.splitText.indices, id:\.self) { index in
switch type {
case .bold:
Text(splitText[index]).fontWeight(.bold)
case .link:
Text(splitText[index]).fontWeight(.bold).foregroundColor(.blue).onTapGesture {
//need to pass this action
handler(splitText[index])
}
default:
Text(splitText[index])
}
}
}
}
struct TextHyperLinkView: View {
var content: [ContentText] = [
ContentText("By completing the form by choosing "),
ContentText("Accept, ", type: .bold),
ContentText("I consent to give …"),
ContentText("Privacy policy", type: .link)]
@State var handler: ((String) -> Void)
@State private var height: CGFloat = 0
var body: some View {
VStack {
GeometryReader { geometry in
ZStack(alignment: .topLeading) {
self.zStackViews(geometry)
}
.background(calculateHeight($height))
}
}.frame(height: height)
.onAppear {
guard let linkContent = content.filter({ $0.type == .button }).first else { return }
//Need Pass handler action here
handler = linkContent.handler
}
}
//other functions
}
// This is my main view
struct PolicyView: View {
var body: some View {
VStack(spacing: 10){
Text("Disclaimer").frame( maxWidth: .infinity, alignment: .leading).font(.system(size: 14))
TextHyperLinkView { value in
//DOESNT GET CALLED
print("handler called \(value)")
}
}.padding()
}
}
任何帮助表示赞赏。