iOS4 - 访问UINavigation堆栈的自定义uiview

时间:2011-11-11 11:36:39

标签: iphone ios4 uiviewcontroller navigation

有点困惑于这个,所以忍受我...

我有一个基于导航的项目,工作正常。我正在尝试创建我的第一个自定义UIView来制作一些我将在多个地方使用的按钮。其中一个按钮需要在点击时将视图控制器推入导航,但我不知道该怎么做。

当我在视图控制器中设置按钮时,我正在使用:

LocationViewController *controller = [[LocationViewController alloc] initWithNibName:@"LocationViewController" bundle:nil];
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];

但是self.navigation控制器现在不能工作了,不是吗?如何访问将添加此uiview的viewcontroller的导航控制器?

希望至少其中一些是有意义的,因为我说这是我第一次进行子视图uiview并将其添加到多个页面,所以我有点迷失。

编辑添加 - 我在自定义UIView中有按钮单击事件,因此我正在尝试更改viewcontroller。我应该将事件连接到我添加视图的视图控制器中吗?

3 个答案:

答案 0 :(得分:0)

使用代码从界面构建器或视图控制器的viewDidLoad添加按钮:

CGRect frame = CGRectMake(0, 0, 24, 24);
UIButton *button = [[UIButton alloc] initWithFrame:frame];
[button addTarget:self action:@selector(handleMyButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

然后在视图控制器中实现-(void)handleMyButton:(id)sender {};。或者您可以使用界面构建器编写-(IBAction)handleMyButton:(id)sender {};并链接方法和按钮。

然后在方法内部粘贴您在上面发布的代码块。如果你开始使用Xcode导航控制器模板项目,它应该可以工作。

我认为hide the designated initializer initWithNibName更清晰:因为它是一个实现细节。

当你说你是UIView的子类时我并不确切地知道你的意思。如果你想用自定义视图添加另一个视图控制器,只需使用UIViewController模板并自定义XIB文件,除非你真正修改它的行为,否则不需要子类化UIView,我想你不是。视图是一个视图,控制器之类的操作按钮应该在控制器中。

答案 1 :(得分:0)

实际控制器需要位于导航控制器堆栈中才能推送另一个控制器。

或者您可以创建一个新的导航控制器实例并推送您的LocationViewController。

答案 2 :(得分:0)

通常你的appDelegate有一个UINavigationController属性。您可以在自定义视图中访问它,如下所示:

UINavigationController *navController = (MyAppDelegate *)[[[UIApplication sharedApplication] 
         delegate] navigationController];

但更有效的方法是在viewController中为自定义视图创建委托方法并处理按钮操作。

MyCustomView.h

    @protocol MyCustomViewDelegate 
    @interface MyCustomView : UIView  {
        id<MyCustomViewDelegate>    cvDelegate; }
    @property(nonatomic, assign) id<MyCustomViewDelegate>   cvDelegate;

    @protocol MyCustomViewDelegate @optional
    -(void)didClickInCustomView:(MyCustomViewDelegate*)view withData:(NSObject*)data; 
    @end

MyCustomView.m

    - (void)myButtonClick:(id)sender 
    { 
        [self.cvDelegate didClickInCustomView:self withData:someData];  
    }

现在,您可以在自定义的任何位置处理此事件 图。

相关问题