我想在 swift UI 中使用 skyfloatingLabelText。他们的示例如下所示
let textField = SkyFloatingLabelTextField(frame: CGRect(x: 10, y: 10, width: 200, height: 45))
textField.placeholder = "Name"
textField.title = "Your full name"
self.view.addSubview(textField)
我不知道如何在我的 swift UI 中实现上述代码。下面是我的快速用户界面。
import SwiftUI
import SkyFloatingLabelTextField
struct Login: View {
var body: some View {
VStack() {
HeaderBar()
Spacer()
HStack {
VStack {
Text("Login Page")
.fontWeight(.bold)
TextField("Name", text: Value) //default input is ok
Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
Text("Login")
}
}
}
Spacer()
}
}
}
struct Login_Previews: PreviewProvider {
static var previews: some View {
Login()
}
}
提前致谢。
最佳答案
就像@Asperi 提到的那样,您需要为此使用 UIViewRepresentable
。
委托(delegate)示例取自 github example .
import SwiftUI
import SkyFloatingLabelTextField
struct SkyFloatingContentView: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {
var parent: SkyFloatingContentView
init(_ parent: SkyFloatingContentView) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
if let text = textField.text {
if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
if (text.count < 3 || !text.contains("@")) {
floatingLabelTextField.errorMessage = "Invalid email"
} else {
// The error message will only disappear when we reset it to nil or empty string
floatingLabelTextField.errorMessage = ""
}
}
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> SkyFloatingLabelTextField {
return SkyFloatingLabelTextField(frame: CGRect(x: 10, y: 10, width: 200, height: 45))
}
func updateUIView(_ textField: SkyFloatingLabelTextField, context: Context) {
textField.placeholder = "Name"
textField.title = "Your full name"
textField.delegate = context.coordinator
}
}
struct ContentView: View {
var body: some View {
VStack() {
Spacer()
HStack {
VStack {
Text("Login Page")
.fontWeight(.bold)
SkyFloatingContentView()
Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
Text("Login")
}
}
}
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
关于swift - 如何在我的 swift UI View 中添加 'skyfloatLabelText'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134273/