在导航栏中添加分段控件

时间:2009-11-05 11:43:46

标签: iphone ios cocoa-touch uinavigationbar uisegmentedcontrol

任何人都可以帮助解决如何在导航栏中添加分段控件的代码....我已经在一些应用程序中看到它并希望实现它

感谢

2 个答案:

答案 0 :(得分:14)

您是否要使用Interface Builder或仅在代码中执行此操作?

使用IB操作非常简单,您只需要将分段控件拖放到标题所在的导航栏上。标题将被分段控件取代。

如果您想在代码中完成此操作,请参阅this section of iPhone reference library。看来你需要将导航项的titleView属性设置为你的分段控件,这是UIView的子类,所以这是完全合法的。

答案 1 :(得分:2)

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;

迅速:

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