我正在努力在 SwiftUI 中找到一种方法来获取 TextField(或任何视图)原点的 x、y 坐标。我当然可以提供一个位置或偏移量来移动视图,但我似乎无法找到一种方法来获取对 TextField 的引用以获取其坐标。
在 UIKit 中,我相信我会使用 myTextField.frame.origin.x
这是一个非常简单的例子:
struct ContentView: View {
@State private var someNumber1 = "1000"
@State private var someNumber2 = "2000"
//bunch more
@State private var enteredNumber = "Some Text at the Top"
@State var value: CGFloat = 0
var body: some View {
ScrollView {
VStack {
Spacer()
Text("\(enteredNumber)")
Spacer()
Group { //1
TextField("Placeholder", text: $someNumber1)
.keyboardType(.default)
.textFieldStyle(RoundedBorderTextFieldStyle())
//this does not work
.onTapGesture {
let aY = (textfieldreferencehere).frame.origin.y
}
TextField("Placeholder", text: $someNumber2)
.keyboardType(.default)
.textFieldStyle(RoundedBorderTextFieldStyle())
}//group 1
//bunch more
Button(action: {
self.enteredNumber = self.someNumber1
self.someNumber1 = ""
UIApplication.shared.endEditing()
}) {
Text("Submit")
}
.padding(.bottom, 50)
}//outer v
.padding(.horizontal, 16)
.padding(.top, 44)
}//Scrollview or Form
.modifier(AdaptsToSoftwareKeyboard())
}
}
Run Code Online (Sandbox Code Playgroud)
任何指导将不胜感激。Xcode 11.4.1
这是如何读取特定视图坐标的演示(请参阅内联有用的评论)
struct DemoReadViewOrigin: View {
@State private var someNumber1 = "1000"
@State private var someNumber2 = "2000"
//bunch more
@State private var enteredNumber = "Some Text at the Top"
@State var value: CGFloat = 0
var body: some View {
ScrollView {
VStack {
Spacer()
Text("\(enteredNumber)")
Spacer()
Group { //1
TextField("Placeholder", text: $someNumber1)
.keyboardType(.default)
.textFieldStyle(RoundedBorderTextFieldStyle())
.background(GeometryReader { gp -> Color in
let rect = gp.frame(in: .named("OuterV")) // < in specific container
// let rect = gp.frame(in: .global) // < in window
// let rect = gp.frame(in: .local) // < own bounds
print("Origin: \(rect.origin)")
return Color.clear
})
//this does not work
.onTapGesture {
}
TextField("Placeholder", text: $someNumber2)
.keyboardType(.default)
.textFieldStyle(RoundedBorderTextFieldStyle())
}//group 1
//bunch more
Button(action: {
self.enteredNumber = self.someNumber1
self.someNumber1 = ""
// UIApplication.shared.endEditing()
}) {
Text("Submit")
}
.padding(.bottom, 50)
}//outer v
.coordinateSpace(name: "OuterV") // << declare coord space
.padding(.horizontal, 16)
.padding(.top, 44)
}//Scrollview or Form
// .modifier(AdaptsToSoftwareKeyboard())
}
}
Run Code Online (Sandbox Code Playgroud)