【发布时间】:2020-04-27 08:27:20
【问题描述】:
当为我的 UISearchbar 调用 searchBarButtonClicked 委托方法时,如何在我的视图类中调用 refresh() 函数?
搜索栏:UIViewRepresentable
import Foundation
import SwiftUI
struct SearchBar: UIViewRepresentable {
@Binding var text: String
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.enablesReturnKeyAutomatically = false
searchBar.searchBarStyle = .minimal
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}
我的视图:视图
import SwiftUI
struct MyView: View {
@State private var searchTerm: String = ""
func refresh() {
//how do i call this function from `SearchBar`?
}
var body: some View {
SearchBar(text: $searchTerm).padding(.top, 5)
}
}
【问题讨论】: