【问题标题】:How to show view controller from custom UIButton class?如何从自定义 UIButton 类显示视图控制器?
【发布时间】:2016-03-28 22:16:34
【问题描述】:

我有以下视图层次结构:导航控制器,在其中我推送了另一个视图控制器,其中包含 UITableView 和单元格中的自定义 UIButtons。我有另一个视图控制器(MyCustomViewController2),我想用动画显示所有这些东西。

但我对这种层次结构感到困惑,我不知道如何在我的自定义 UIButton 类中覆盖 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 方法。我到目前为止的代码是:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    MyCustomViewController2 *myVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"MyVC"];
    [self.window addSubview: myVC.view];
}

但这太糟糕了!而且我没有任何动画,我应该删除它以删除。接下来我可以尝试什么?

【问题讨论】:

    标签: objective-c uiview uiviewcontroller uibutton uiview-hierarchy


    【解决方案1】:

    It's highly recommended not to subclass a UIButton. 所以我不会。

    但是由于UIButton是UIControl的子类,所以可以直接使用这个方法:

    - (void)addTarget:(id)target
               action:(SEL)action
     forControlEvents:(UIControlEvents)controlEvents
    

    代码中的示例可能如下所示:

    [self.myButton addTarget:self action:@selector(showOtherVC) forControlEvents: UIControlEventTouchUpInside];
    

    当用户从按钮上抬起手指时,这将查看特定方法 (showOtherVC) 的目标 (self)

    然后,您可以让当前的 View Controller 使用这个 UIViewController 方法作为示例以模态方式呈现新的 View Controller:

    -(void)showOtherVC
    {
         MyCustomViewController2 *myVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"MyVC"];
        [self presentViewController:myVC animated:true completion:nil];
    }
    

    在此处阅读有关 UIControl 的更多信息: UIControl Documentation

    并在此处查看其他 UIViewController 模态转换样式: UIViewController Documentation

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 2019-09-14
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多