如何通过单击按钮显示 swift 中其他 viewController Class 的视图

How to show a view from other viewController Class in swift with button click

我这里有两个 viewController 类 1) 搜索购物车 viewController 2) 搜索医学 Viewcontroller 在我的搜索车控制器中,有一个在情节提要中设计的 UiView(名为:lineItemView)。在搜索药物控制器中,我有一个添加药物的按钮。我想如果我从搜索药物控制器单击添加药物按钮,它应该从搜索购物车控制器弹出 lineItemView 并且应该隐藏搜索购物车控制器本身。我尝试使用 UserDefalts,但它不起作用。添加按钮点击

@IBAction func addMedicineBtnTapped(_ sender: Any) {
  
    let defaults = UserDefaults.standard
    defaults.set(true, forKey: "showLineItemView")
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "searchCart") as!  searchCart
    vc.finalcart = cart
    vc.storeCart()
    self.navigationController?.pushViewController(vc, animated: true)

}

在搜索购物车中加载功能

if UserDefaults.standard.value(forKey: "showLineItemView") != nil{
              let condition = UserDefaults.standard.value(forKey: "showLineItemView") as! Bool
              if condition{
                 self.view.isHidden= true
                self.lineItemView.isHidden = false
                UserDefaults.standard.set(false, forKey: "showLineItemView")
              }
         }

解决方案:

@IBAction func addMedicineBtnTapped(_ sender: Any) {
  
    let defaults = UserDefaults.standard
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "searchCart") as!  searchCart
    vc.finalcart = cart
    vc.storeCart()
    vc.showLineItemView = true
    vc.modalPresentationStyle = .overFullScreen
    //push as NavigationController
    //self.navigationController?.pushViewController(vc, animated: true)
    //push as UIViewController
    self.present(vc, animated: false, completion: nil) 

}


class searchCart:UIViewController{
    var showLineItemView = false

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if(showLineItemView){
            self.view.backgroundColor = .clear
            //disable all other UI
            self.lineItemView.isHidden = false
        }
    }
    //close seach cart
    func lineItemDone(){
        self.dismiss(animated: false, completion: nil)
    }
}

使用另一个 viewcontroller 子视图不是一个好主意,尝试为 lineItemView 创建组件 UI(XIB),让 lineItemView 由原点 viewcontroller 控制。