【问题标题】:Click button quickly push UIViewController twice点击按钮快速推送 UIViewController 两次
【发布时间】:2016-01-30 15:01:08
【问题描述】:

示例:

我在当前视图中有两个按钮,当我单击按钮时,它将在当前UINavgitionController 中推送一个UIViewController

这是我的代码:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.navigationController?.pushViewController(pvc, animated: true)
})

但我发现了一个错误。当我快速点击按钮时,UIViewController 按了两次,为什么会这样?

PS:现在,我已经在UIViewControllers 中多次使用此代码,超过 200 次。

【问题讨论】:

  • 有了你的代码,它就会发生。 dispatch_async(dispatch_get_main_queue() 不会立即执行。您可以在单击后禁用该按钮。
  • @anhtu 是对的。希望您了解异步和同步调用的概念。
  • 现在当你点击它两次时,它会向你发送两次命令到队列中。与异步调用一样,它们中的每一个都会在它们运行时被调用,从而导致两次推送 VC。
  • 如果你点击按钮两次,那么它将导航两次。所以你已经放置了加载程序或活动指示器,直到控件导航到屏幕...

标签: ios iphone swift uinavigationcontroller pushviewcontroller


【解决方案1】:

我也遇到了同样的问题,我通过创建 UIButton 类别解决了这个问题,它只需要独占触摸。

创建 UIButton 的类别

#import <objc/runtime.h> //Please import

    @implementation UIButton (ExclusiveTouch)

    + (void)load
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Class class = [self class];

            SEL originalSelector = @selector(willMoveToSuperview:);
            SEL swizzledSelector = @selector(inc_willMoveToSuperview:);

            Method originalMethod = class_getInstanceMethod(class, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

            BOOL didAddMethod =
            class_addMethod(class,
                            originalSelector,
                            method_getImplementation(swizzledMethod),
                            method_getTypeEncoding(swizzledMethod));

            if (didAddMethod) {
                class_replaceMethod(class,
                                    swizzledSelector,
                                    method_getImplementation(originalMethod),
                                    method_getTypeEncoding(originalMethod));
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod);
            }
        });
    }

    - (void)inc_willMoveToSuperview:(UIView *)newSuperview
    {
        // This is correct and does not cause an infinite loop!
        // See the link for an explanation
        [self inc_willMoveToSuperview:newSuperview];

        [self setExclusiveTouch:YES];
    }

【讨论】:

  • 你能告诉我如何使用它吗? @ROCKING-XCode
猜你喜欢
  • 2013-05-08
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 2020-10-08
  • 2012-07-26
相关资源
最近更新 更多