使用Tap Gesture

时间:2016-09-01 03:28:10

标签: ios objective-c mobile uiviewcontroller svprogresshud

我需要向SVProgressHUD添加UITapGestureRecognizer。 SVProgressHUD已经能够使用-(void) dismiss;解雇。此代码将根据秒数关闭动画。

- (void)dismiss {
for (UIGestureRecognizer *gesture in [[[self class] sharedView] gestureRecognizers]) {
    [[[self class] sharedView] removeGestureRecognizer:gesture];
}

NSDictionary *userInfo = [self notificationUserInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification
                                                    object:nil
                                                  userInfo:userInfo];

self.activityCount = 0;
[UIView animateWithDuration:0.15
                      delay:0
                    options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8, 0.8);
                     if(self.isClear) // handle iOS 7 UIToolbar not answer well to hierarchy opacity change
                         self.hudView.alpha = 0;
                     else
                         self.alpha = 0;
                 }
                 completion:^(BOOL finished){
                     if(self.alpha == 0 || self.hudView.alpha == 0) {
                         self.alpha = 0;
                         self.hudView.alpha = 0;

                         [[NSNotificationCenter defaultCenter] removeObserver:self];
                         [self cancelRingLayerAnimation];
                         [self addTapGestureToDismiss];
                         [_hudView removeFromSuperview];
                         _hudView = nil;

                         [_overlayView removeFromSuperview];
                         _overlayView = nil;

                         [_indefiniteAnimatedView removeFromSuperview];
                         _indefiniteAnimatedView = nil;


                         UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                         [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification
                                                                             object:nil
                                                                           userInfo:userInfo];

                         // Tell the rootViewController to update the StatusBar appearance
                         UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;
                         if ([rootController respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
                             [rootController setNeedsStatusBarAppearanceUpdate];
                         }
                         // uncomment to make sure UIWindow is gone from app.windows
                         //NSLog(@"%@", [UIApplication sharedApplication].windows);
                         //NSLog(@"keyWindow = %@", [UIApplication sharedApplication].keyWindow);
                     }
                 }];

}

我的思维过程是将tapGesture代码添加到dismiss方法。这就是我到目前为止所写的内容。

- (void)addTapGestureToDismiss {

// Creation and initializer of the tap gesture
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(dismiss)];

// Specify that the gesture must be a single tap
tapRecognizer.numberOfTapsRequired = 1;

// Add the tap gesture recognizer to the view
[[[self class] sharedView] addGestureRecognizer:tapRecognizer];

}

正如您所看到的,我只是初始化tapGesture。我遇到了将它放在几个地方并导致应用程序只有一次点击的问题。我在这个过程中几乎让自己感到困惑。我应该

  • 将此手势添加到视图中?
  • 添加此手势以解散?

5 个答案:

答案 0 :(得分:8)

根据Z.Hung的回答,您可以在SVProgressHUD上创建一个类别,这样您就不必在每个使用它的视图控制器中重复此代码。

<强>用法

只需导入此类别并致电

[SVProgressHUD showDismissableErrorWithStatus:@"Error message here"];

<强>代码

@interface SVProgressHUD (Dismissable)

+ (void)showDismissableErrorWithStatus:(NSString*)status;

@end

@implementation SVProgressHUD (Dismissable)

+ (void)showDismissableErrorWithStatus:(NSString*)status {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleHUDTappedNotification:) name:SVProgressHUDDidReceiveTouchEventNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleHUDDisappearedNotification:) name:SVProgressHUDWillDisappearNotification object:nil];
    [SVProgressHUD showErrorWithStatus: status];
}

#pragma mark - NSNotificationCenter

+ (void)handleHUDTappedNotification: (NSNotification *)notification {
    [SVProgressHUD dismiss];
}

+ (void)handleHUDDisappearedNotification: (NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDDidReceiveTouchEventNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDWillDisappearNotification object:nil];

}

@end

Swift 4

import SVProgressHUD

/// Ref: https://stackoverflow.com/a/41111242/425694
extension SVProgressHUD {

  public static func showDismissableError(with status: String) {
    let nc = NotificationCenter.default
    nc.addObserver(
      self, selector: #selector(hudTapped(_:)),
      name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent,
      object: nil
    )
    nc.addObserver(
      self, selector: #selector(hudDisappeared(_:)),
      name: NSNotification.Name.SVProgressHUDWillDisappear,
      object: nil
    )
    SVProgressHUD.showError(withStatus: status)
    SVProgressHUD.setDefaultMaskType(.clear)
  }

  @objc
  private static func hudTapped(_ notification: Notification) {
    SVProgressHUD.dismiss()
    SVProgressHUD.setDefaultMaskType(.none)
  }

  @objc
  private static func hudDisappeared(_ notification: Notification) {
    let nc = NotificationCenter.default
    nc.removeObserver(self, name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent, object: nil)
    nc.removeObserver(self, name: NSNotification.Name.SVProgressHUDWillDisappear, object: nil)
    SVProgressHUD.setDefaultMaskType(.none)
  }

}

答案 1 :(得分:2)

UPDATE 2.0

After a while I stumbled upon this solution and remembered this question, it works as far as I have tested. Just add a Observer in your viewWillAppear of your ViewController class. No need to modify the library like my previous answer.

-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tapToDismiss:) name:SVProgressHUDDidReceiveTouchEventNotification object:nil];
    //Other initializing
}
-(void)tapToDismiss:(NSNotification *)notification{
    [SVProgressHUD dismiss];
    //maybe other code to stop whatever your progress is
}

This should dismiss the SVProgressHUD even if you have a masktype.

Use this to remove the Observer after you're done (like in the viewDidDisappear) or it will be there throughout the lifetime of the app.

[[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDDidReceiveTouchEventNotification object:nil];

Credit: http://kevsaidwhat.blogspot.my/2013/06/cancel-svprogresshud-process-by-tapping.html

答案 2 :(得分:0)

完整的快速实施可能有人会觉得有用。这是BaseViewController

func showProgressHud(){
    SVProgressHUD.show()
    SVProgressHUD.setDefaultMaskType(.clear)
}

func hideProgressHud(){
    SVProgressHUD.dismiss()
}


//Hide progress hud on user tap on unresponsive api call

func hideProgressHudOnUserTap(){
    NotificationCenter.default.addObserver(self, selector: #selector(self.tapToDismiss(notification:)), name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent, object: nil)
}

@objc func tapToDismiss(notification: Notification) {
    hideProgressHud()
}

func removeProgressHudObserver(){
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent, object: nil)
}

然后您像这样在视图控制器中调用它

override func viewWillAppear(_ animated: Bool) {
    hideProgressHudOnUserTap()
}

override func viewDidDisappear(_ animated: Bool) {
    removeProgressHudObserver()
}

答案 3 :(得分:0)

一种简单的实现方法是:

  1. 创建一个消除HUD的类:
class HUDManager {
    @objc
    class func dismissHUD() {
        SVProgressHUD.dismiss()
    }
}
  1. 订阅SVProgressHUDDidReceiveTouchEvent通知:
NotificationCenter.default.addObserver(HUDManager.self,
                                       selector: #selector(HUDManager.dismissHUD),
                                       name: .SVProgressHUDDidReceiveTouchEvent,
                                       object: nil)

答案 4 :(得分:0)

感谢@charmingToad,如果这里有答案,我想在上面发布一些经过优化和实用的解决方案。

就我而言,如果用户点击并取消操作,我需要知道取消操作以取消操作。

import SVProgressHUD

extension SVProgressHUD {
    private static var dismissCompletion: (() -> ())?
    
    public static func showDismissable(with status: String, tapDismissed: (() -> ())? = nil) {
        dismissCompletion = tapDismissed
        
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(
            self, selector: #selector(hudTapped(_:)),
            name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent,
            object: nil
        )
        notificationCenter.addObserver(
            self, selector: #selector(hudDisappeared(_:)),
            name: NSNotification.Name.SVProgressHUDWillDisappear,
            object: nil
        )
        SVProgressHUD.show(withStatus: status)
        SVProgressHUD.setDefaultMaskType(.black)
    }

  @objc
  private static func hudTapped(_ notification: Notification) {
    SVProgressHUD.dismiss()
    SVProgressHUD.setDefaultMaskType(.none)
    dismissCompletion?()
  }

  @objc
  private static func hudDisappeared(_ notification: Notification) {
    dismissCompletion = nil
    let notificationCenter = NotificationCenter.default
    notificationCenter.removeObserver(self, name: NSNotification.Name.SVProgressHUDDidReceiveTouchEvent, object: nil)
    notificationCenter.removeObserver(self, name: NSNotification.Name.SVProgressHUDWillDisappear, object: nil)
    SVProgressHUD.setDefaultMaskType(.none)
  }
}