5

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

谢谢

4

2 回答 2

14

您想使用 Interface Builder 还是仅在代码中使用?

使用IB操作非常简单,只需将分段控件拖动到标题所在的导航栏上即可。标题将被分段控件替换。

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

于 2009-11-05T11:52:52.060 回答
2

viewDidLoad

对象-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
于 2015-06-05T09:48:54.460 回答