Swift扩展navigationBar的高度并添加segmentControl

我devise了下面的UINavigationBar,但是我有点困惑,是否有可能像下面这样添加segmentControl? 什么是最好的方式来实现这样的?

在这里输入图像说明

U导航栏的扩展。 (对不起,彼得的问题没有回答。)

在Xcode中,File – New – Swift File – 命名类。

import UIKit import Foundation extension UINavigationController { func makeBlackNavigationbar (){ print("black navigation") navigationController?.navigationBarHidden = false } } extension UINavigationBar { func makeBlackNavigationBar () { barTintColor = UIColor.blackColor() let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] titleTextAttributes = titleDict as [NSObject : AnyObject] } } 

它可以在项目的任何地方实施。

 self.navigationController?.makeBlackNavigationbar() self.navigationController?.navigationBar.makeBlackNavigationBar() 

你可以模仿你的要求如下:

 -(void) segmentAction: (UISegmentedControl *) segmentedControl { // Update the label with the segment number NSString *segmentNumber = [NSString stringWithFormat:@"%0d", segmentedControl.selectedSegmentIndex + 1]; [(UITextView *)self.view setText:segmentNumber]; } - (void) loadView { [super loadView]; // Create a central text view UITextView *textView = [[UITextView alloc] initWithFrame:self.view.frame]; textView.font = [UIFont fontWithName:@"Futura" size:96.0f]; textView.textAlignment = UITextAlignmentCenter; self.view = textView; // Create the segmented control NSArray *buttonNames = [NSArray arrayWithObjects: @"Recent", @"Popular", @"My", nil]; UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:buttonNames]; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.momentary = YES; [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; // Add it to the navigation bar self.navigationItem.titleView = segmentedControl; } 

或者有另一种方法如下:

 UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: [NSArray arrayWithObjects: [NSString stringWithString:NSLocalizedString(@"Recent", @"")], [NSString stringWithString:NSLocalizedString(@"Popular", @"")], [NSString stringWithString:NSLocalizedString(@"My", @"")], nil]]; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.tintColor = [UIColor clearColor]; [segmentedControl setSelectedSegmentIndex:0]; [segmentedControl addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged]; [segmentedControl setFrame:[self.navigationController.toolbar bounds]]; [self.navigationController.toolbar addSubview:segmentedControl];