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

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
}

10-08 16:41