我已经整合了一个UIView
,其中包含完全在其自己的实现代码中的平移,捏合和旋转手势识别器,因此它可以在任何视图控制器中工作,即使是一个零代码(除了关闭Xcode中的自动布局。
#import "Subview.h"
@interface Subview () <UIGestureRecognizerDelegate>
@end
@implementation Subview
- (void)awakeFromNib
{
[self addGestureRecognizer:[[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateView:)]];
[self addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panView:)]];
[self addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchView:)]];
for (UIGestureRecognizer * gr in self.gestureRecognizers){
gr.delegate = self;
}
}
// delegate method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
// gesture actions:
- (void)rotateView:(UIRotationGestureRecognizer *)sender
{
[self adjustAnchorPointForGestureRecognizer:sender];
if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
self.transform = CGAffineTransformRotate(self.transform, sender.rotation);
sender.rotation = 0;
}
}
- (void)panView:(UIPanGestureRecognizer *)sender
{
[self adjustAnchorPointForGestureRecognizer:sender];
if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [sender translationInView:self.superview];
[self setCenter:CGPointMake(self.center.x + translation.x, self.center.y + translation.y)];
[sender setTranslation:CGPointZero inView:self.superview];
}
}
- (void)pinchView:(UIPinchGestureRecognizer *)sender
{
[self adjustAnchorPointForGestureRecognizer:sender];
if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
sender.scale = 1.0;
}
}
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint locationInView = [sender locationInView:self];
CGPoint locationInSuperview = [sender locationInView:self.superview];
self.layer.anchorPoint = CGPointMake(locationInView.x / self.bounds.size.width, locationInView.y / self.bounds.size.height);
self.center = locationInSuperview;
}
}
@end
到目前为止它工作得很好并且编译器没有给出警告,但是我不确定视图是否设置了自己的框架和中心,并且是自己的委托。但它确实有助于清理视图控制器,并且感觉非常整洁和便携。那么这实际上是否会导致任何微妙的错误或违反任何最佳实践规则?