常規(guī)思路,移動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的視覺呈現(xiàn)是通過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];
}