【问题标题】:UISegmentedControl within UIView does not respond to change eventUIView 中的 UISegmentedControl 不响应更改事件
【发布时间】:2014-05-16 21:34:06
【问题描述】:

我在 iOS7 SDK 上以编程方式创建了一个基本应用程序:

  1. 创建了两个 UINavigationController
  2. 为每个人添加了一个视图
  3. 创建了一个包含两个项目的 UITabBarController
  4. 将每个 UINavigationController 添加到其各自的 UITabBarController

一切正常,一切都以编程方式完成。我的项目只包含一个简单的窗口应用程序模板,没有任何 xib 或故事板,一切都在我的 AppDelegate.m 的 application didFinishLaunchingWithOptions: 中完成。

我正在尝试添加一个 UISegmentedControl(仍以编程方式)作为第一个 UINavigationController 视图的子视图,如下所示:

// 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];

UISegmentedControl 确实出现了,但没有处理触摸事件。

如果我更改代码并直接在 UINavigationController 中添加 UISegmentedControl,触摸事件实际上是在响应:

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

我做错了什么,我应该怎么做才能让它响应它的触摸事件?

【问题讨论】:

    标签: ios objective-c ios7 uiview uisegmentedcontrol


    【解决方案1】:

    您需要设置视图的大小。

    令人困惑的是,即使视图太小而无法容纳其内容,但只会响应其官方尺寸区域上的触摸。

    【讨论】:

    • 你明白了,为视图设置一个框架确实解决了这个问题。顺便说一句,我应该注意到我为该视图设置的黄色没有出现!所以现在我应该回到我的实际项目中,了解为什么我的 UISegmentedControl 的父级没有实际大小。
    • “视图的大小”/“官方大小”是什么意思?设置视图的框架,它包括大小。还是我错了?
    • @rommex 4 年前所以记忆有点模糊。我相信我的意思是:需要设置父视图的帧大小。 segmentedControl 有框架,但 firstView 没有
    【解决方案2】:

    您不应该将子视图直接添加到导航控制器视图。

    'firstView' 应该被封装到 UIViewController 中。并使用 [[UINavigationController alloc] initWithRootViewController:myFirstViewController];

    创建您的导航控制器

    【讨论】:

    • 我的项目只是一个小小的概念证明,因为我只是想重新创建一个简单的环境来解决我正在尝试迁移到 iOS7 的更广泛项目中出现的问题。我完全同意通过各自的控制器处理视图的需要。
    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多