Adding Segmented Controls Using the Navigation Bar

can someone help with the code on how to add a segmented control to the navigation bar .... I saw it in some applications and I want to implement it

thanks

+5
source share
2 answers

Do you want to use Interface Builder or do it only in code?

When working with IB is very simple, you only need to drag the segmented control to place it on the navigation bar where the name is located. The title will be replaced by the segmented control.

, iPhone. , titleView , UIView, .

+14

viewDidLoad:

OBJ-:

NSArray *segmentTitles = @[
    @"segment1",
    @"segment2",
];

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTitles];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// change the width from 400.0 to something you want if it needed
segmentedControl.frame = CGRectMake(0, 0, 400.0f, 30.0f);
[segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];

self.navigationItem.titleView = segmentedControl;

:

let segmentTitles = [
    "segment1",
    "segment2",
]

let segmentedControl = UISegmentedControl(items: segmentTitles)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.autoresizingMask = UIViewAutoresizing.FlexibleWidth
// change the width from 400.0 to something you want if it needed
segmentedControl.frame = CGRectMake(0, 0, 400.0, 30.0)
segmentedControl.addTarget(self, action: "segmentChanged:", forControlEvents: UIControlEvents.ValueChanged)

self.navigationItem.titleView = segmentedControl
+1

All Articles