adding segmented control with in the Navigation Bar
-
16-09-2019 - |
Question
can anybody help with the code on how to add segmented control within the navigation bar....i have seen it on some applications and want to implement it
thanks
Solution
Do you want to use Interface Builder or do it in code only?
With IB operation is very straightforward, you only need to drag segmented control to place on navigation bar where title is located. Title will be replaced by the segmented control.
If you want to accomplish this in code, please refer to this section of iPhone reference library. It seems you need to set navigation item's titleView
property to your segmented control, which is subclass of UIView, so this is completely legal.
OTHER TIPS
in viewDidLoad
:
obj-c:
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's needed
segmentedControl.frame = CGRectMake(0, 0, 400.0f, 30.0f);
[segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = segmentedControl;
swift:
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's needed
segmentedControl.frame = CGRectMake(0, 0, 400.0, 30.0)
segmentedControl.addTarget(self, action: "segmentChanged:", forControlEvents: UIControlEvents.ValueChanged)
self.navigationItem.titleView = segmentedControl
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow