常规思路,移动frame,这种方法是行不通的,在按钮移动的时候,只能点击按钮的最终位置才会响应事件,点击按钮本身是无效的.代码如下
- (void)viewDidLoad {
[super viewDidLoad];
[self uiConfig];
}
- (void)uiConfig
{
_btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
_btn.backgroundColor = [UIColor purpleColor];
[_btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
[UIView animateWithDuration:10.f delay:2.f options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear animations:^{
_btn.frame = CGRectMake(0, 400, 100, 100);
} completion:^(BOOL finished) {
}];
}
- (void)btnClick
{
_btn.backgroundColor = [UIColor colorWithRed:(arc4random()%255)/ 255.f green:(arc4random()%255)/ 255.f blue:(arc4random()%255)/ 255.f alpha:1];
}
既然frame行不通,我们改用layer层,因为btn的视觉呈现是通过layer层,这里会用到一个很重要的属性,presentationLayer.
- (void)uiConfig
{
_btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
_btn.backgroundColor = [UIColor purpleColor];
[_btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
[UIView animateWithDuration:10.f delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear animations:^{
_btn.layer.transform = CATransform3DMakeTranslation(0, 400, 0);
} completion:^(BOOL finished) {
}];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = touches.anyObject;
CGPoint touchPoint = [touch locationInView:self.view];
if (CGRectContainsPoint(((CALayer *)[_btn.layer presentationLayer]).frame, touchPoint))
{
[self btnClick];
}
}
- (void)btnClick
{
_btn.backgroundColor = [UIColor colorWithRed:(arc4random()%255)/ 255.f green:(arc4random()%255)/ 255.f blue:(arc4random()%255)/ 255.f alpha:1];
}