答案 0 :(得分:1)
您应该将分段控件添加为导航栏的titleView
。
以下是示例代码:
let titles = ["All", "Missed"]
segmentControl = UISegmentedControl(items: titles)
segmentControl.tintColor = UIColor.white
segmentControl.backgroundColor = UIColor.blue
segmentControl.selectedSegmentIndex = 0
for index in 0...titles.count-1 {
segmentControl.setWidth(120, forSegmentAt: index)
}
segmentControl.sizeToFit()
segmentControl.addTarget(self, action: #selector(segmentChanged), for: .valueChanged)
segmentControl.selectedSegmentIndex = 0
segmentControl.sendActions(for: .valueChanged)
navigationItem.titleView = segmentControl
答案 1 :(得分:1)
您可以尝试以下简单代码
var segmentedController: UISegmentedControl!
let items = ["Label A", "Label B"]
segmentedController = UISegmentedControl(items: items)
navigationItem.titleView = segmentedController
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.rightBarButtonItem?.tintColor = UIColor.black
答案 2 :(得分:1)
如果要使用XIB添加UISegmentControl,则可以按照以下简单步骤进行操作:
将代码放入ViewController
class ViewController: UIViewController {
lazy var navSegmentedView: YourCustomView = {
guard let aView = Bundle.main.loadNibNamed("\(YourCustomView.self)", owner: self, options: nil)?.first as? YourCustomView else { return YourCustomView() }
aView.backgroundColor = .clear
aView.frame = CGRect(x: 0, y: 0, width: 160, height: 40)
aView.segmentControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
return aView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
func setupNavBar() {
navigationItem.titleView = navSegmentedView
navigationItem.titleView?.backgroundColor = .clear
}
@objc func segmentChanged(_ sender: UISegmentedControl) {
print(sender.selectedSegmentIndex)
}
}