close

將SwiftUI 的view加到UIViewController上,

使用 UIHostingController,

    
// MARK: - Swift UI voew
    
    private lazy var swiftuiSearchBarController: UIHostingController = {
        let host = UIHostingController(rootView: SearchBar(viewModel: self.viewModel.searchBarViewModel))
        return host
    }()
    
    private var swiftuiSearchBar: UIView {
        return swiftuiSearchBarController.view
    }

    

 

 

self.addChild(swiftuiSearchBarController) // fix: SwiftUI view 的onChange不會被觸發 <- 這行是關鍵,加完 UIHostingController's view後,要有這行

    
/// 將SwiftUI searchBar view加到畫面上,tableView, autoTableView與searchBar用stackView包起來
    private func initSearchBar() {
        let stackView = UIStackView.vStack(spacing: 0) { _ in
            let view = UIView.view { view in
                view.addSubview(tableView)
                view.addSubview(autoTableView)
                
                tableView.snp.makeConstraints { make in
                    make.edges.equalTo(0)
                }
                
                autoTableView.snp.makeConstraints { make in
                    make.edges.equalTo(0)
                }
            }

            return [
                swiftuiSearchBar,
                view
            ]
        }
        self.view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        self.addChild(swiftuiSearchBarController) // fix: SwiftUI view 的onChange不會被觸發
    }

    
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小賢 的頭像
    小賢

    小賢的部落格

    小賢 發表在 痞客邦 留言(0) 人氣()