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

时间:2017-04-13 00:50:25

标签: swift xcode uisegmentedcontrol programmatically-created

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

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

} 

1 个答案:

答案 0 :(得分:6)

初始化后,您应该将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
}