我正在尝试使用此处的解决方案为该人员发布的问题重新创建相同类型的解决方案。可以在我的代码下面的/或下面的链接中找到假定的解决方案。但是,这些都不能说我正在使用“未声明的类型'Length'”。这个问题是在7个月前提出的,因此我确定这与在SwiftUI中使用各种语法的新方法有关
How to make view the size of another view in SwiftUI
旧问题的文字说: “我正在尝试重新创建Twitter iOS应用程序的一部分以学习SwiftUI,并且想知道如何动态地将一个视图的宽度更改为另一视图的宽度。在我的情况下,下划线应与文本视图。”
import SwiftUI
extension HorizontalAlignment {
private enum UnderlineLeading: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> Length {
return d[.leading]
}
}
static let underlineLeading = HorizontalAlignment(UnderlineLeading.self)
}
struct GridViewHeader : View {
@State private var activeIdx: Int = 0
@State private var w : [Length] = [0, 0, 0, 0]
var body: some View {
return VStack(alignment: .underlineLeading) {
HStack {
Text("Tweets").modifier(MagicStuff(activeIdx: $activeIdx, widths: w, idx: 0))
Spacer()
Text("Tweets & Replies").modifier(MagicStuff(activeIdx: $activeIdx, widths: w, idx: 1))
Spacer()
Text("Media").modifier(MagicStuff(activeIdx: $activeIdx, widths: w, idx: 2))
Spacer()
Text("Likes").modifier(MagicStuff(activeIdx: $activeIdx, widths: w, idx: 3))
}
.frame(height: 50)
.padding(.horizontal, 10)
Rectangle()
.alignmentGuide(.underlineLeading) { d in d[.leading] }
.frame(width: w[activeIdx], height: 2)
.animation(.basic())
}
}
}
struct MagicStuff: ViewModifier {
@Binding var activeIdx: Int
@Binding var widths: [Length]
let idx: Int
func body(content: Content) -> some View {
Group {
if activeIdx == idx {
content.alignmentGuide(.underlineLeading) { d in
DispatchQueue.main.async { self.widths[self.idx] = d.width }
return d[.leading]
}.onTapGesture { self.activeIdx = self.idx }
} else {
content.onTapGesture { self.activeIdx = self.idx }
}
}
}
}
struct GridViewHeader_Previews: PreviewProvider {
static var previews: some View {
GridViewHeader()
}
}