如何将segmentControl附加到NavigationBar?

时间:2018-07-11 15:19:05

标签: ios swift uikit uisegmentedcontrol

我尝试将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()

它看起来应该像: Sample

1 个答案:

答案 0 :(得分:2)

尝试此代码

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