Search code examples
iosswiftuikituisegmentedcontrol

How to attach segmentControl to NavigationBar?


I try to attach UISegmentedControl in navigation bar, but somethings going wrong:

Segment control:

func segmentControl() -> UIView {
let newUIView = UIView()

newUIView.backgroundColor = UIColor.clear
newUIView.layer.cornerRadius = 15.0

let items = ["list", "map"]
let customSC = UISegmentedControl(items: items)

customSC.layer.cornerRadius = 15.0
customSC.layer.borderWidth = 1
customSC.layer.borderColor = UIColor.green.cgColor

customSC.clipsToBounds = true
customSC.tintColor = UIColor.green

let font = UIFont.systemFont(ofSize: 16)
customSC.setTitleTextAttributes([NSAttributedStringKey.font: font],
                                for: .normal)

newUIView.addSubview(customSC)

return newUIView
}

And I try to attach with:

SomeTab.navigationItem.titleView = segmentControl()

It should look like a: Sample


Solution

  • Try this code

    let segment: UISegmentedControl = UISegmentedControl(items: ["First", "Second"])
    segment.sizeToFit()
    segment.tintColor = UIColor(red:0.99, green:0.00, blue:0.25, alpha:1.00)
    segment.selectedSegmentIndex = 0;
    segment.setTitleTextAttributes([NSFontAttributeName: UIFont(name:"ProximaNova-Light", size: 15)!],
                forState: UIControlState.Normal)
    self.navigationItem.titleView = segment