3

我正在尝试将 a 添加到仅一个视图(而不是整个视图控制器)UISegmentedControl的中间。UINavigationBar我该怎么做呢?

我阅读的其他答案只允许整个视图控制器包含 aUINavigationItem作为标题。我需要它只在一个视图上显示。

4

3 回答 3

5

此代码将为您提供帮助。

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                            [NSArray arrayWithObjects:@"Add",@"Delete",
                                             nil]];
    segmentedControl.frame = CGRectMake(0, 0, 80, 30);
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentedControl setWidth:35.0 forSegmentAtIndex:0];
    [segmentedControl setWidth:45.0 forSegmentAtIndex:1];

    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    segmentedControl.momentary = YES;

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    [segmentedControl release];

    self.navigationItem.leftBarButtonItem = segmentBarItem;
    [segmentBarItem release];

这段代码的结果是

在此处输入图像描述

编辑:

可以工作的确切代码:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                            [NSArray arrayWithObjects:@"Add",@"Delete",
                                             nil]];
    segmentedControl.frame = CGRectMake(0, 0, 80, 30);
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentedControl setWidth:35.0 forSegmentAtIndex:0];
    [segmentedControl setWidth:45.0 forSegmentAtIndex:1];

    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    segmentedControl.momentary = YES;

    self.navigationItem.titleView = segmentedControl;
于 2012-12-31T09:47:50.213 回答
3

您可以将 UISegmentedControl 作为 SubView 添加到导航栏。

NSArray *arrayOfItems = [[NSArray alloc] initWithObjects:@"A",@"B",@"C", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:arrayOfItems];
segmentedControl.frame=CGRectMake(60, 0, 200, 44);
[self.navigationController.navigationBar addSubview:segmentedControl];
于 2012-12-31T13:20:03.417 回答
1

如果要添加以任何视图为中心的 UISegmentedControl,而不仅仅是 UINavigationView:

UISegmentedControl *segmentedTab = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]];
segmentedTab.center = CGPointMake(segmentedView.frame.size.width / 2, segmentedView.frame.size.height / 2);
[self.segmentedView addSubview:segmentedTab];

segmentedView 是一个包含我们的 UISegmentedControl 的视图。

于 2014-05-05T12:00:34.040 回答