如果你想访问和修改变量,你应该添加 __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);
}];
这是你追求的东西吗?