ios 如何在 UINavigationBar 中添加 UISegmentedControl?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30504503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:06:18  来源:igfitidea点击:

How to add the UISegmentedControl in UINavigationBar?

iosuitableviewuinavigationbaruisegmentedcontrol

提问by Hymany Shek

I have tried to add the UISegmentedControlto the bottom of UINavigationBarwith title. But i cannot add it and I cannot add UISegmentedControlin the tableView.headerView,because i need the search bar in the tableView.headerView, so there is just one solution that i need to add UISegmentedControlto the bottom of UINavigationBar. Anyone have another idea that i can solve this situation?

我试图将标题添加UISegmentedControl到底部UINavigationBar。但我不能添加它,我不能添加UISegmentedControltableView.headerView,因为我需要在搜索栏tableView.headerView,所以只有一个解决方案,我需要添加UISegmentedControl到的底部UINavigationBar。有人有其他想法我可以解决这种情况吗?

Here is the code that I have tried(with Swift):

这是我尝试过的代码(使用Swift):

        class searchingViewController: UITableViewController{ 
                override func viewDidLoad() {         
                    var items: [AnyObject] = ["Searching Method A", "Searching Method B"]
                    var searchSC:UISegmentedControl!
                    searchSC.frame = CGRectMake(0, 0, frame.width - 20, 30)
                    searchSC.selectedSegmentIndex = 1
                    searchSC.backgroundColor = UIColor(white: 1, alpha: 1)
                    searchSC.layer.cornerRadius = 5.0
                    navigateUIToolBar = UIToolbar(frame: CGRectMake(frame.minX + 10, ios7_8Info.getStatusBarHeight()+self.navigationController!.navigationBar.frame.height+frame.minY+(21/2),
                        frame.width - 20, 30))

                    navigateUIToolBar.addSubview(searchSC)
                    self.navigationController?.navigationBar.addSubview(navigateUIToolBar)
                  }
          }

回答by Hardik Thakkar

To add segment control in UINavigationBar in Swift 5

在 Swift 5 中的 UINavigationBar 中添加段控件

    let segment: UISegmentedControl = UISegmentedControl(items: ["First", "Second"])
    segment.sizeToFit()
    if #available(iOS 13.0, *) {
        segment.selectedSegmentTintColor = UIColor.red
    } else {
       segment.tintColor = UIColor.red
    }
    segment.selectedSegmentIndex = 0
    segment.setTitleTextAttributes([NSAttributedString.Key.font : UIFont(name: "ProximaNova-Light", size: 15)!], for: .normal)
    self.navigationItem.titleView = segment

回答by Magoo

To put it in the navigationBar has a right left and title view for such things... accessed using....

把它放在导航栏中有一个左右和标题视图这样的东西......访问使用......

self.navigationItem.titleView = mySegmentedControl

self.navigationItem.titleView = mySegmentedControl

for future reference....

备查....

self.navigationItem.rightBarButtonItem
self.navigationItem.leftBarButtonItems // for adding an Array of items

To add it below the navigation view but have it static.. add it to the viewController.view... Are you using a UITableViewController? If so maybe switch to a UIViewController and add a tableView then your toolbarview as subviews to that self.view.

要将其添加到导航视图下方但使其静态...将其添加到 viewController.view... 您是否使用 UITableViewController?如果是这样,可能切换到 UIViewController 并添加一个 tableView,然后您的工具栏视图作为该 self.view 的子视图。

回答by Abhishek

I think you are looking for this.

我想你正在寻找这个。

let searchVC = self.storyboard?.instantiateViewController(withIdentifier:"idofcontroller")
let searchController = UISearchController(searchResultsController: searchVC)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
navigationItem.searchController = searchController
definesPresentationContext = true

searchController.searchBar.scopeButtonTitles = ["News", "Photos", "Videos"]
searchController.searchBar.delegate = self

enter image description here

在此处输入图片说明

回答by koen

This is how I do it in Objective C (sorry, I haven't learned Swift yet):

这就是我在 Objective C 中的做法(抱歉,我还没有学过 Swift):

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.viewControllers = [self segmentViewControllers];

    self.segmentedControl = [[UISegmentedControl alloc] initWithItems: [self.segmentedControl addTarget: self
                          action: @selector(segmentClicked:)
                forControlEvents: UIControlEventValueChanged];

    CGFloat topOffset = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;

    self.toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, topOffset, self.navigationController.navigationBar.frame.size.width, kDefaultViewHeight)];
    self.toolbar.delegate = self;

    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.toolbar.backgroundColor = [UIColor whiteColor];
    self.toolbar.clipsToBounds = YES;

    UIBarButtonItem *segmentedControlItem = [[UIBarButtonItem alloc] initWithCustomView: self.segmentedControl];
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace
                                                                              target: nil
                                                                              action: nil];

    [self.toolbar setItems: @[flexibleItem, segmentedControlItem, flexibleItem] animated: YES];

    [self.navigationController.view addSubview: self.toolbar];

    self.segmentedControl.selectedSegmentIndex = 0;
}

And in UITableViewController (one of the segmentViewControllers):

在 UITableViewController(segmentViewControllers 之一)中:

  self.tableView.contentInset = UIEdgeInsetsMake(topOffset, 0, 0, 0);

    CGRect currentFrame = self.tableView.frame;
    [self.tableView setFrame: CGRectMake(currentFrame.origin.x,
                                     currentFrame.origin.y,
                                     currentFrame.size.width,
                                     currentFrame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height)];

回答by williamwu

you can custom navigationItem's titleView, like this:

您可以自定义导航项的 titleView,如下所示:

self.navigationItem.titleView = segmentview

you should not add subview to the navigationbar, for after push or pop UIViewcontroller ,the subview is still exsit on the navigationbar.

你不应该向导航栏添加子视图,因为在推送或弹出 UIViewcontroller 之后,子视图仍然存在于导航栏上。

回答by Dominic Holmes

You can also add the segment control to a search bar, not the navigation item. If you're like me, I needed a large title + search bar + navigation item, which would be impossible with the current top answer.

您还可以将段控件添加到搜索栏,而不是导航项。如果您像我一样,我需要一个大标题 + 搜索栏 + 导航项,这对于当前的最佳答案是不可能的。

@Abhishek 's answer is close. You would do something like the following:

@Abhishek 的答案很接近。您将执行以下操作:

// Create the search controller
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.scopeButtonTitles = ["Option 1", "Option 2"]

// Make sure the scope bar is always showing, even when not actively searching
searchController.searchBar.showsScopeBar = true

// Make sure the search bar is showing, even when scrolling
navigationItem.hidesSearchBarWhenScrolling = false

// Add the search controller to the nav item   
navigationItem.searchController = searchController
definesPresentationContext = true

@Gurjit Singh, the line with .showsScopeBar = trueis the solution to your problem.

@Gurjit Singh,.showsScopeBar = true您的问题是解决方案。