【问题标题】:Handle popViewControllerAnimated like event in another class?在另一个类中处理 popViewController 类似事件的动画?
【发布时间】:2014-09-17 10:21:32
【问题描述】:

我必须在每个 ViewController 中创建一个相同的按钮。所以我决定写一个有这个功能的类。我创建了一个类名 MyUtils 并向 UINavigationItem 添加了一个后退按钮,它可以正确显示,但不知道如何在该类中添加一个事件。

它显示准确,但没有执行任何事件。我的意思是 popViewControllerAnimated:YES

我喜欢叫 myUtil

MyUtil *utils = [[MyUtil alloc] init];

[utils NavAndBackBtn:self.navigationItem];

MyUtil.m

-(void)NavAndBackBtn:(UINavigationItem *)nav 
{

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

[btn setImage:[UIImage imageNamed:@"icon_back.png"] forState:UIControlStateNormal];

//[btn setTarget:self action:@selector(popView) forControlEventTouchUPInside];

[button setFrame:CGRectMake(0,0,36,20);

UIBarButtonItem *barbtn = [[UIBarButton alloc] initWithCustomView:btn];

nav.leftBarButtonItem = barbtn;// this gives error

}
-(void)popView
{
// [self.navigationController popViewControllerAnimated:YES];  //not working no method in self
}

但不知道如何在 MyUtil 类中向 popViewControllerAnimated:YES 添加事件。因为我在那里没有 self 的参考。

popView 方法

必须有一种方法来获取类的上下文。我的意思是这个班上的自己。并代表它添加事件。并且没有 UINavigationItem 方法会弹出ViewController。

简单来说 我只想在我在 MyUtils 创建的那个按钮上 popViewController 事件。但它必须在MyUtils 类中实现。我怎样才能在另一个类中 popViewControllerAnimated。

【问题讨论】:

    标签: objective-c uinavigationcontroller uinavigationitem


    【解决方案1】:
    -(void)showBackBarButton:(UIViewController*)controller{
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn setTitle:@"Back" forState:UIControlStateNormal];
        [btn addTarget:controller.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
        [btn setFrame:CGRectMake(0,0,36,30)];
         UIBarButtonItem *barbtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
        controller.navigationItem.leftBarButtonItem=barbtn;
    }
    

    开启ViewDiDLoad

        [utils showBackBarButton:self];
    

    【讨论】:

    • 现在我有 UINavigationItem 而不是 UINavigationController 。它是 UINavigationController 的一个方法。而 nav 在这里是一个 UINavigationItem 。任何其他解决方案
    • 通过发送 self.navigationController 。我无法在该类中获得 nav.navigationItem.leftBarButton 。出于这个原因,我将其更改为navigationItem。我也不知道在持有 NavigationController 时为什么我无法在该类中获取 navigationItem。我已经尝试过这个解决方案。它甚至不显示我的按钮
    • 非常感谢。现在我明白了如何发送上下文,因为我有 android 背景..
    • 主要是你的目标,
    猜你喜欢
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多