【问题标题】:Replicate block animation ios [UIView animateWithDuration:...]复制块动画ios [UIView animateWithDuration:...]
【发布时间】:2013-12-03 19:38:50
【问题描述】:

我想复制类似内置UIView 类方法+animateWithDuration:animations:completion: 的东西。所以基本上我正在尝试用一个可以访问/操作内部变量的块编写一个方法。

类似这样的:

int dur = 0.5;

[MyClass changeWithDuration:dur manipulations:^{

    // I want to access these values and change them to the following values
    // in 'dur' seconds, just like the built-in UIView class function does 

    myVariable = 0.5;
    myOtherVariable = 1; 

}];

我想在Cocoa 应用程序中使用它,所以使用UIView 类方法是不可能的。

【问题讨论】:

    标签: ios objective-c macos cocoa objective-c-blocks


    【解决方案1】:

    如果你想访问和修改变量,你应该添加 __block 关键字:

    __block int dur = 0.5;
    
    [MyClass changeWithDuration:dur manipulations:^{
    
        // I want to access these values and change them to the following values
        // in 'dur' seconds, just like the built-in UIView class function does 
    
        myVariable = 0.5;
        myOtherVariable = 1; 
    
        //Now you can change value go due variable
        dur = 2.5;
    
    }];
    

    如果您要访问某个对象,有时您需要创建对该对象的弱引用以避免保留循环。

    //扩展

    如果你想做类似于 UIView 动画块的事情,请在 .h 文件中声明方法:

    // This just save typings, you don't have to type every time 'void (^)()', now you have to just type MyBlock
    typedef void (^MyBlock)();
    
    @interface MyClass : UIView
    
    -(void)changeWithDuration:(float)dur manipulations:(MyBlock)block;
    
    @end
    

    在你的 .m 文件中:

    -(void)changeWithDuration:(float)dur manipulations:(MyBlock)block
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:dur];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
        if (block)
            block();
    
        [UIView commitAnimations];
    }
    

    要调用你可以做的方法:

         vi = [[MyView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
        [vi setBackgroundColor:[UIColor redColor]];
        [self.view addSubview:vi];
        [vi changeWithDuration:3 manipulations:^{
            vi.frame = CGRectMake(250, 20, 50, 40);
        }];
    

    这是你追求的东西吗?

    【讨论】:

    • 你知道 UIView 类方法是如何工作的吗?这就是我试图实现的目标,而不是你在这里的建议。我知道如何在块中操作变量,我需要从这个块中“提取”这些变量并插入/操作它们......
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多