为什么导航栏中分段控件的选择器不起作用?

Why does the selector of my segmented control in a navigation bar not work?

第一期:
我可以在段之间切换,但应用程序无法识别切换并且从不运行选择器功能。

第二期:
导航栏标题不显示。

代码如下:

class ViewController: UIViewController {

    let mySegmentControl: UISegmentedControl = {
        let sc = UISegmentedControl(items: ["First","Second","Third"])
        sc.translatesAutoresizingMaskIntoConstraints = false
        sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
        sc.selectedSegmentIndex = 0

        if #available(iOS 13.0, *) {
            sc.selectedSegmentTintColor = .red
        } else {
            // Fallback on earlier versions
            sc.tintColor = .red
        }
        return sc
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationController?.navigationBar.tintColor = .blue
        navigationController?.navigationBar.barTintColor = .yellow
        navigationItem.title = "My App"
        self.navigationItem.titleView = mySegmentControl
    }

    @objc func handleSegmentChange() {
        let chosedIndex = mySegmentControl.selectedSegmentIndex
        print(chosedIndex)
    }
}

在您创建 mySegmentConstrol 的闭包中,self 并不是您认为的那样。在这种情况下,self 指的是 (ViewController) -> () -> ViewController 类型的东西,这绝对 不是 你想要的:

要引用当前的 ViewController 实例,请将 mySegmentControl 声明为 lazy var:

lazy var mySegmentControl: UISegmentedControl = {

这应该会让您的分段控件选择器正确触发。

至于显示导航项的 title,好吧......你真的不能那样做 在导航栏的 [=19] 中显示自定义视图=].非此即彼。