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

Time:01-19

I have two viewController classes as here 1)Search cart viewController 2)Search Medicine Viewcontroller in my search cart controller there is a UiView(named: lineItemView) designed in storyboard. In search medicine controller i have a button to add medicine. I want if i click on add medicine button from search medicine controller it should popup lineItemView from search cart controller and search cart controller itself should be hidden. I try with UserDefalts but it is not working. add on button click

@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)

}

in search cart didload function

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")
              }
         }

CodePudding user response:

solution:

@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)
    }
}

Use another viewcontroller child view is not a good idea, try to make component UI(XIB) for lineItemView, let lineItemView is controled by origin viewcontroller.

  •  Tags:  
  • Related