如何将段控件附加到导航栏?

How to attach segmentControl to NavigationBar?

我尝试在导航栏中附加 UISegmentedControl,但出了点问题:

段控制:

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
}

我尝试附加:

SomeTab.navigationItem.titleView = segmentControl()

它应该看起来像:

试试这个代码

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