如何制作iOS回调函数?

Pio*_*rCh 4 objective-c callback ios

我无法弄清楚如何创建一个函数,它将向父对象提供已完成某项操作的信息,因此我需要您的帮助.示例我要做的:

  1. ViewControllerclass实例化类BottomView并将其添加为子视图.
  2. BottomView类的实例上调用以启动动画.
  3. 动画结束后,我想给出一个动画已经结束的标志ViewController,它可以BottomView从自身释放/删除一个实例.

我需要像回调一样的东西.你能帮帮忙吗?

Pau*_*l.s 12

你可以这样做

@interface BottomView : UIView

@property (nonatomic, copy) void (^onCompletion)(void);

- (void)start;

@end

@implementation BottomView

- (void)start
{
  [UIView animateWithDuration:0.25f
                   animations:^{
                     // do some animation
                   } completion:^(BOOL finished){
                     if (self.onCompletion) {
                       self.onCompletion();
                     }
                   }];
}

@end
Run Code Online (Sandbox Code Playgroud)

您将使用哪种

BottomView *bottomView = [[BottomView alloc] initWithFrame:...];
bottomView.onCompletion = ^{
  [bottomView removeFromSuperview];
  NSLog(@"So something when animation is finished and view is remove");
};
[self.view addSubview:bottomView];
[bottomView start];
Run Code Online (Sandbox Code Playgroud)


Ber*_*rgP 6

你可以用积木来做!

您可以将一些块传递给BottomView.

或者你可以通过目标行动来做到这一点.

您可以将BottomView选择器@selector(myMethod:)作为操作传递给视图控制器作为目标.动画结束后使用performeSelector:方法.

3.或者您可以在viewController中定义委托@protocol并实现方法, 并在BottomView中添加委托属性.@property(assign)id delegate;

如果在BottomView中制作动画,可以使用 UIView方法

animateWithDuration:delay:options:animations:completion:
Run Code Online (Sandbox Code Playgroud)

使用块作为回调

[UIView animateWithDuration:1.0f animations:^{

    }];
Run Code Online (Sandbox Code Playgroud)

更新:

在ButtomView.h中

@class BottomView;

@protocol BottomViewDelegate <NSObject>

- (void)bottomViewAnimationDone:(BottomView *) bottomView;

@end


@interface BottomView : UIView

@property (nonatomic, assign) id <BottomViewDelegate> delegate;

.....
@end 
Run Code Online (Sandbox Code Playgroud)

在ButtomView.m中

- (void)notifyDelegateAboutAnimationDone {
   if ([self.delegate respondsToSelector:@selector(bottomViewAnimationDone:)]) {
      [self.delegate bottomViewAnimationDone:self];
   }
}
Run Code Online (Sandbox Code Playgroud)

在动画complit之后你应该打电话 [self notifyDelegateAboutAnimationDone];

你应该设置ViewController类来确认协议BottomViewDelegate

在MyViewController.h中

  @interface MyViewController : UIViewController <BottomViewDelegate>
...
@end
Run Code Online (Sandbox Code Playgroud)

viewDidLoad你应该设置bottomView.delegate = self;