以编程方式在导航栏中嵌入分段控件

programmatically embedding segmented control inside navigation bar

我试图以编程方式在导航栏中插入分段控件,但在导航栏中加载分段控制器时遇到了一些问题。我相信这很简单,但请参阅下面的代码。提前致谢!

var segmentedController: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.titleView = segmentedController
    let items = ["Label A", "Label B"]
    segmentedController = UISegmentedControl(items: items)

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
    navigationItem.leftBarButtonItem?.tintColor = UIColor.black

} 

segmentedController初始化后应该添加到导航栏中!

var segmentedController: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()

    let items = ["Label A", "Label B"]
    segmentedController = UISegmentedControl(items: items)
    navigationItem.titleView = segmentedController

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
    navigationItem.leftBarButtonItem?.tintColor = UIColor.black
}