Вопрос

I have programmatically created a basic app on iOS7 SDK :

  1. Created two UINavigationController
  2. Added a view to each of them
  3. Created a UITabBarController with two items
  4. Added each UINavigationController to its respective UITabBarController

This is working fine, and everything is done programmatically. My project only consists in a simple window app template, without any xib nor storyboard, and everything is done within application didFinishLaunchingWithOptions: of my AppDelegate.m.

I am trying to add a UISegmentedControl (still programmatically) as a subview of the view of the first UINavigationController, as follows :

// First navigation controller
UINavigationController *firstNavController = [[UINavigationController alloc] init];
firstNavController.navigationBar.barTintColor = [UIColor redColor];
firstNavController.title = @"First";
firstNavController.navigationBar.topItem.title = @"First top";
firstNavController.tabBarItem.image = [UIImage imageNamed:@"FirstTab"];

// First view
UIView *firstView = [[UIView alloc] init];
firstView.backgroundColor = [UIColor yellowColor];

// Add a segmented control to this view
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
            [NSArray arrayWithObjects:@"One", @"Two", nil]];
// Register an event handler
[segmentedControl addTarget:self action:@selector(segmentedControlSelectedIndexDidChange:)
           forControlEvents:UIControlEventValueChanged];
// Shape it and select its first item
segmentedControl.frame = CGRectMake(10, 100, 300, 20);
segmentedControl.selectedSegmentIndex = 1;

// add the segmented control to the view
[firstView addSubview:segmentedControl];

// and the view to the first tab's navigation controler
[firstNavController.view addSubview:firstView];

The UISegmentedControl DOES show up, but touch events are not handled.

If I change my code and add the UISegmentedControl directly within the UINavigationController, touch events are actually responding :

// and the segmented control directly within the navigation controller
[firstNavController.view addSubview:segmentedControl];

What am I doing wrong, and what should I do to have it respond to it's touch events ?

Это было полезно?

Решение

You need to set the size of the view.

Confusingly a view will be visible even if it is too small to fit it's content but will only respond to touches over the area of it's offical size.

Другие советы

You should not be adding a subview directly to the navigation controllers view.

'firstView' should be encapsulated into a UIViewController. And create your navigation controller with [[UINavigationController alloc] initWithRootViewController:myFirstViewController];

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top