【问题标题】:How to call a void method with arguments with a delay?如何延迟调用带有参数的 void 方法?
【发布时间】:2013-11-06 03:20:17
【问题描述】:

我有一个 void 方法,此方法将 UIView 动画到一个点,在特定时间后 UIView 应该 animate 到另一个点,我正在尝试使用 [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(METHOD) userInfo:nil repeats:NO]; 来执行此操作,但它看起来就像我不能用Arguments 做空一样。我需要执行这个 void:

-(void)showNotificationViewWithText:(NSString *)title andTextColor:(UIColor *)titleTintColor andNotificationBackGroundColor:(UIColor *)backGroundColor andDuration:(float)duration direction:(BOOL) up:

或者有没有人有更好的想法在延迟后将 UIView 移动到不同的点?

【问题讨论】:

    标签: ios objective-c arguments void


    【解决方案1】:

    在延迟一段时间后执行任何代码的一种非常灵活的方法是 GCD 函数 dispatch_after()。它需要一个 block 作为参数,您可以在其中调用 具有任意参数和返回类型的任何方法:

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // do whatever you want, e.g.
        [self showNotificationViewWithText: ....];
    });
    

    (提示:只需在 Xcode 编辑器中输入“dispatch_after”,剩下的就交给自动补全了!)

    【讨论】:

    • 这是迄今为止最简洁的解决方案
    • 谢谢,最好的解决方案!
    【解决方案2】:

    您可以使用 NSObject 类的performSelector:withObject:afterDelay: 方法。

     NSDictionary *obj = [[NSDictionary alloc] initWithObjectsAndKeys:title,@"title",titleTintColor,@"titleTintColor",backGroundColor,@"backGroundColor",[NSNumber numberWithFloat:duration],@"duration",[NSNumber numberWithBool:up],@"up" nil];
     [self performSelector:@selector(showNotificationViewWithText:) withObject:obj afterDelay:2.0];  
    
    -(void)showNotificationViewWithText:(NSDictionary *)arg
    {
        NSDictionary *title = [arg objectForkey:@"title"];
        UIColor      *titleTintColor = [arg objectForkey:@"titleTintColor"];
        UIColor      *backGroundColor = [arg objectForkey:@"backGroundColor"];
        float        duration = [arg objectForkey:@"duration"];
        BOOL         up = [arg objectForkey:@"up"];
    
        //code
    }
    

    【讨论】:

    • 好的,谢谢,但我有多个对象,没有对象的方法
    • 你可以传递参数的NSDictionary。
    • 你最终会得到这个工作,但Martin R's solution要好得多。
    【解决方案3】:

    在调度计时器时很简单,只需通过 nstimer 争论。试试这样:-

         [NSTimer    
       scheduledTimerWithTimeInterval:duration 
        target:self selector:@selector(METHOD:) 
       userInfo:nil repeats:NO];
    
    
      -(void)METHOD:(NSTimer*) timer
      {
     // your code
       }    
    

    【讨论】:

      【解决方案4】:

      或者有没有人有更好的想法将 UIView 移动到不同的点 延迟之后?

      如果您为视图设置动画,您可以在动画方法中指定延迟

      + (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        • 2011-03-05
        • 1970-01-01
        • 2016-10-01
        相关资源
        最近更新 更多