如何在SubView移动过程中使动画SubView中的按钮工作?

Piy*_*hur 5 objective-c uiview uiviewanimation ios

在下面的代码中,带按钮的子视图会振荡,即从原点水平移动到红色区域并返回.

但它没有获得按钮本身的点击,而是接收红色区域的点击.

在此输入图像描述

我想在动画SubView中使用此按钮在SubView仅在x轴上移动时工作.

在这项技术的初级阶段,我在这里陷入困境.

下面分别是.h和.m文件的代码.

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UIView *viewWithButton;
}
@property (strong, nonatomic) UIView *viewWithButton;
- (void) animateButton;

@end
Run Code Online (Sandbox Code Playgroud)

ViewController.m

@implementation ViewController

@synthesize viewWithButton;

- (void) animateButton
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:10];
    [UIView setAnimationRepeatCount:HUGE_VALF];
    [UIView setAnimationRepeatAutoreverses:YES];

    CGPoint pos = viewWithButton.center;
    pos.x = 400;
    viewWithButton.center = pos;

    [UIView commitAnimations];
}
- (IBAction)btn
{
    NSLog(@"Button Tapped");
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*hit 0

尝试一下这个希望对你有帮助。取一个数组并将按钮添加到该数组中。

@property (nonatomic, retain) NSMutableArray *arrBtn;
[self.arrBtn addObject:btn];
Run Code Online (Sandbox Code Playgroud)

制作类似这样的动画

[UIView animateWithDuration:8.0f
                      delay:0.0f
                    options:UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                 }
                 completion:^(BOOL finished){   
                 }];
Run Code Online (Sandbox Code Playgroud)

添加此方法来取得联系

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    for (UIButton *button in self.arrBtn)
    {
        if ([button.layer.presentationLayer hitTest:touchLocation])
        {
            // This button was hit whilst moving - do something with it here
            NSLog(@"button title is %@",button.titleLabel.text);
            [button setBackgroundColor:[UIColor cyanColor]];
            NSLog(@"Button Clicked");
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)