UISegmentedControl click not fire when click

45 Views Asked by At

I encountered a problem: VC contains UISegmentedControl, I used NavigationController Push this VC. When UISegmentedControl is clicked, the Click event is not fired.

let items = ["Photos", "Map"]

lazy var segmentedControl: UISegmentedControl = {
     let SC = UISegmentedControl( items: items)

     //- size of this segmentedControl:
     SC.widthAnchor.constraint(equalToConstant: 200).isActive = true
     SC.translatesAutoresizingMaskIntoConstraints = false
     SC.selectedSegmentIndex = 0
     SC.addTarget(self, action: #selector(didTapSegmentedControl), for: .valueChanged)
     return SC

}()

let VC1:Photos
let VC2:PlaceMap

init(){
     self.VC1 = Photos()
     self.VC2 = PlaceMap()

     super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
     fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
     super.viewDidLoad()

     view.backgroundColor = .white

     setUpViews()
     setUpSegmentedControl()
}

func setUpSegmentedControl(){
     addChild(VC1)
     addChild(VC2)

     self.view.addSubview(VC1.view)
     self.view.addSubview(VC2.view)

     VC1.didMove(toParent:self )
     VC2.didMove(toParent:self )

     VC1.view.frame = CGRect(x: 0, y: 90, width: view.bounds.width, height: view.bounds.height)
     VC2.view.frame = CGRect(x: 0, y: 90, width: view.bounds.width, height: view.bounds.height)

     VC2.view.isHidden = true
}

@objc func didTapSegmentedControl(){
     VC1.view.isHidden = true
     VC2.view.isHidden = true

     if ( segmentedControl.selectedSegmentIndex == 0 ) {
         self.VC1.view.isHidden = false
     } else {
         // show VC2 : Map
         self.VC2.view.isHidden = false
     }
}

-- add segmentedControl
func setUpViews(){
        
        view.addSubview(imgBackwardArrow)
        view.addSubview(segmentedControl)
        
        NSLayoutConstraint.activate([
        
            imgBackwardArrow.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 2),
            imgBackwardArrow.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 12),
            imgBackwardArrow.widthAnchor.constraint(equalToConstant:35),
            imgBackwardArrow.heightAnchor.constraint(equalToConstant:35),
            //
            //segmentedControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 2),
            segmentedControl.topAnchor.constraint(equalTo: view.topAnchor,constant: 60),
             segmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        ])
        
        //- hook
        let singleTapClose = UITapGestureRecognizer(target: self,action: #selector(didTapBackwardArrowBtn))
        imgBackwardArrow.isUserInteractionEnabled = true
        imgBackwardArrow.addGestureRecognizer(singleTapClose)
    }
0

There are 0 best solutions below