【问题标题】:SwiftUI, call function in view after something happens in UIViewRepresentableSwiftUI,在 UIViewRepresentable 发生某些事情后在视图中调用函数
【发布时间】: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)
    }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    我可以使用 NotificationCenter 解决这个问题

    1. 通知扩展

      // MARK: - NSNotification
      extension NSNotification {
          static let SearchPressed = NSNotification.Name.init("SearchPressed")
      }
      
    2. 将观察者添加到 onReceive

      var body: some View {
          VStack {
              //...
          }.onReceive(NotificationCenter.default.publisher(for: NSNotification.SearchPressed)) { _ in
          self.refresh() }
      }
      
    3. 将此Notification post 添加到委托方法中:searchBarSearchButtonClicked

      NotificationCenter.default.post(name: NSNotification.SearchPressed,
          object: nil, userInfo: nil)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多