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

时间:2014-05-09 10:20:10

标签: ios objective-c uiview uiviewanimation

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

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

enter image description here

我希望在SubView在x轴上移动时,在动画SubView中创建此按钮。

在这项技术的初级阶段,我遇到了困难。

以下是.h和.m文件的代码。

ViewController.h

#import <UIKit/UIKit.h>

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

@end

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");
}

1 个答案:

答案 0 :(得分:0)

试试这个希望它会对你有所帮助。取一个数组并将你的按钮添加到该数组。

@property (nonatomic, retain) NSMutableArray *arrBtn;
[self.arrBtn addObject:btn];

制作像这样的动画

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

添加此方法以获取触摸

- (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;
        }
    }
}