复制块动画ios [UIView animateWithDuration:...]

时间:2013-12-03 19:38:50

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

我想复制内置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类方法是不可能的。

2 个答案:

答案 0 :(得分:0)

如果要访问和修改变量,则应添加__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;

}];

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

//扩展

如果你想在.h文件中执行类似于UIView动画块声明方法的内容:

// 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);
    }];

这是你要追求的东西吗?

答案 1 :(得分:0)

好吧,似乎不太可能......

复制

  

iOS - Getting a variable from inside a block passed as a parameter