1

我想创建一个应用程序,其中导航控制器作为窗口根视图控制器和导航控制器标题视图中的分段控件以切换其根视图控制器

问题:将分段控制添加到 nag 控制器后不存在

代码:

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{  
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    FirstViewController * fc = [[FirstViewController alloc] initWithNibName:@"FirstView" bundle:nil];

    UINavigationController * nc = [[UINavigationController alloc] initWithRootViewController:fc];
    [fc release];

    self.window.rootViewController = nc;

    NSArray * array = [NSArray arrayWithObjects:@"GPS",@"List",@"Map", nil];

    UISegmentedControl * sc = [[UISegmentedControl alloc] initWithItems:array];

    sc.frame = CGRectMake(0, 0, 250, 50);
    sc.segmentedControlStyle = UISegmentedControlStylePlain;

    [nc.navigationItem setTitleView:sc];

    [sc release];
    [nc release];

    [self.window makeKeyAndVisible];

    return YES;
}
4

1 回答 1

0

您正在为 NavigationItem 设置 titleView 而不是为它设置 Item 。

NSArray * array = [NSArray arrayWithObjects:@"GPS",@"List",@"Map", nil];

UISegmentedControl * sc = [[UISegmentedControl alloc] initWithItems:array];
sc.frame = CGRectMake(0, 0, 250, 50);
sc.segmentedControlStyle = UISegmentedControlStylePlain;

要在标题视图中设置,请使用此行

[ViewController.navigationItem setTitleView:sc];

设置左或右您不能直接将项目添加到导航栏,因此使用您的段控件创建 BarButtonItem

UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:sc];

将其添加到 ViewController 而不是 NavigationController

[ViewController.navigationItem setRightBarButtonItem:segmentItem];
于 2013-04-09T11:00:26.033 回答