Gemini/Gemini-iOS/HomepagePrefView.swift

97 lines
2.8 KiB
Swift
Raw Normal View History

2021-06-16 03:21:22 +00:00
//
// HomepagePrefView.swift
// Gemini-iOS
//
// Created by Shadowfacts on 6/15/21.
//
import SwiftUI
struct HomepagePrefView: View {
@State private var url: URL? = Preferences.shared.homepage
@State private var focus = false
var body: some View {
List {
// use a custom binding to allow the state variable to be nil temporarily, and update the pref when not
HomepagePrefTextField(value: Binding(get: {
url
}, set: { (newVal) in
self.url = newVal
if let newVal = newVal {
Preferences.shared.homepage = newVal
}
}), focus: $focus)
}
.navigationBarTitle("Homepage")
.onAppear {
focus = true
}
.onDisappear {
// if the text field was empty when we disappeared, reset to the default homepage
if url == nil {
Preferences.shared.homepage = AppDelegate.defaultHomepage
}
} }
}
struct HomepagePrefTextField: UIViewRepresentable {
@Binding private var value: URL?
@Binding private var focus: Bool
init(value: Binding<URL?>, focus: Binding<Bool>) {
self._value = value
self._focus = focus
}
func makeUIView(context: Context) -> UITextField {
let field = UITextField()
field.addTarget(context.coordinator, action: #selector(Coordinator.textChanged), for: .editingChanged)
field.clearButtonMode = .whileEditing
field.placeholder = AppDelegate.defaultHomepage.absoluteString
// fix for text field expanding horizontally when text grows
field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return field
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = value?.absoluteString
context.coordinator.binding = $value
if focus {
DispatchQueue.main.async {
uiView.becomeFirstResponder()
focus = false
}
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(binding: $value)
}
class Coordinator: NSObject {
var binding: Binding<URL?>
init(binding: Binding<URL?>) {
self.binding = binding
}
@objc func textChanged(_ textField: UITextField) {
if let text = textField.text,
!text.isEmpty {
if let url = URL(string: text) {
binding.wrappedValue = url
}
} else {
binding.wrappedValue = nil
}
}
}
}
struct HomepagePrefView_Previews: PreviewProvider {
static var previews: some View {
HomepagePrefView()
}
}