如何将分段控件添加到导航栏? (IOS)

时间:2018-04-10 02:32:58

标签: ios swift xcode user-interface navigationbar

我想将分段控件添加到这样的导航栏中 enter image description here

但是当我将分段控件拖到导航栏时,大标题就消失了。如何创建上述UI?

3 个答案:

答案 0 :(得分:1)

您应该将分段控件添加为导航栏的titleView。 以下是示例代码:

let titles = ["All", "Missed"]
segmentControl = UISegmentedControl(items: titles)
segmentControl.tintColor = UIColor.white
segmentControl.backgroundColor = UIColor.blue
segmentControl.selectedSegmentIndex = 0
for index in 0...titles.count-1 {
    segmentControl.setWidth(120, forSegmentAt: index)
}
segmentControl.sizeToFit()
segmentControl.addTarget(self, action: #selector(segmentChanged), for: .valueChanged)
segmentControl.selectedSegmentIndex = 0
segmentControl.sendActions(for: .valueChanged)
navigationItem.titleView = segmentControl

答案 1 :(得分:1)

您可以尝试以下简单代码

var segmentedController: UISegmentedControl!

let items = ["Label A", "Label B"]
segmentedController = UISegmentedControl(items: items)
navigationItem.titleView = segmentedController
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.rightBarButtonItem?.tintColor = UIColor.black

答案 2 :(得分:1)

如果要使用XIB添加UISegmentControl,则可以按照以下简单步骤进行操作:

  1. 在XIB中设计您的自定义视图(请参考XIB以供参考https://i.stack.imgur.com/AJDCo.png
  2. 将代码放入ViewController

    class ViewController: UIViewController {
    
        lazy var navSegmentedView: YourCustomView = {
            guard let aView = Bundle.main.loadNibNamed("\(YourCustomView.self)", owner: self, options: nil)?.first as? YourCustomView else { return YourCustomView() }
    
            aView.backgroundColor = .clear
            aView.frame = CGRect(x: 0, y: 0, width: 160, height: 40)
            aView.segmentControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
    
            return aView
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            setupNavBar()
        }
    
        func setupNavBar() {
            navigationItem.titleView = navSegmentedView
            navigationItem.titleView?.backgroundColor = .clear
        }
    
        @objc func segmentChanged(_ sender: UISegmentedControl) {
            print(sender.selectedSegmentIndex)
        }
    
     }