How to add the UISegmentedControl in UINavigationBar?

前端 未结 6 1353
遥遥无期
遥遥无期 2021-02-04 03:44

I have tried to add the UISegmentedControl to the bottom of UINavigationBar with title. But i cannot add it and I cannot add UISegmentedControl

6条回答
  •  别跟我提以往
    2021-02-04 04:33

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

    - (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):

      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)];
    

提交回复
热议问题