我想在快速用户界面中使用 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)
我不知道如何在快速的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()
}
}
谢谢。
答案 0 :(得分:1)
就像@Asperi一样,您需要为此使用UIViewRepresentable
。
委托示例摘自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()
}
}