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

问题描述 投票:0回答:1

第一个问题。 我可以在段之间切换,但应用程序不识别切换,永远不会运行选择器功能。

第二个问题:我的导航栏标题不显示。 导航栏的标题不显示。

screenshot

下面是代码。

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)
    }
}
ios swift uinavigationbar uisegmentedcontrol
1个回答
0
投票

在你创建的封闭内 mySegmentConstrol, self 并不是您所认为的那样。在这种情况下 self(ViewController) -> () -> ViewController,这绝对是 您想要的东西。

Some weird type

要参考当前 ViewController 例如,声明 mySegmentControl 作为 lazy var:

lazy var mySegmentControl: UISegmentedControl = {

这应该能让你的分段控制选择器正常启动。

至于显示你的导航项的 title嗯... ... 你不能真正做到这一点。 在导航栏中显示一个自定义的视图 titleView. 要么选择一个,要么选择另一个

© www.soinside.com 2019 - 2024. All rights reserved.