UISegmentedControl in TitleView with Swift July 28, 2016

Adding a UISegmentedControl into the TitleView of a Navigation Bar is a bit tricky. I was able to accomplish it with Swift 3.0 like this:

            func setupSegmentedControl() {
        let items = ["Register", "Sign In"]
        customSC = UISegmentedControl(items: items)
        customSC.selectedSegmentIndex = 0
        
        let frame = UIScreen.main.bounds
    
        customSC.frame = CGRect(x: frame.minX + 10, y: frame.minY+50, width: frame.width - 20, height: frame.height)
        customSC.layer.cornerRadius = 5.0
        customSC.backgroundColor = UIColor.white
        customSC.tintColor = hexStringToUIColor(hex: "#006B99")
        
        customSC.addTarget(self, action: #selector(toggleRegisterSignIn), for: .valueChanged)

        self.view.addSubview(customSC)

        let size = self.customSC.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
        self.customSC.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        
        self.navigationItem.titleView = customSC
      }
        

That's it! Have fun and #CompileSwift.