在iPhone编程中,子视图应该更改自己的帧和中心,还是超级视图应该更改它们?

在iPhone编程中,子视图应该更改自己的帧和中心,还是超级视图应该更改它们?,iphone,frame,subview,superview,Iphone,Frame,Subview,Superview,我需要用户能够在屏幕上拖动子视图来更改子视图的位置。我知道这两种方法都有可能,但有一种方法更可取吗?为什么呢?如果您使用的是iOS 3.2或更高版本,请查看UIPangestureRecognitor // **** other Code **** UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)]; pan

我需要用户能够在屏幕上拖动子视图来更改子视图的位置。我知道这两种方法都有可能,但有一种方法更可取吗?为什么呢?

如果您使用的是iOS 3.2或更高版本,请查看UIPangestureRecognitor

// **** other Code ****
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];

panGesture.delegate = self;
[dragView addGestureRecognizer:panGesture];
[panGesture release];
}

- (void)panGesture:(UIPanGestureRecognizer *)gestureRecognizer 
{
    CGPoint location = [gestureRecognizer locationInView:parentView]; // The view the of the drag item is in
    gestureRecognizer.view.center = location;
}

这一切都是从内存中完成的,但它应该是这样的,完全基于MVC的概念,任何负责该视图的都应该处理泛手势识别器。至少,我是这么做的。视图本身不应该真正关心或意识到它正在被移动

现在,对于类似缩放或滚动的内容,这似乎与视图相关(例如,
UIScrollView
具有
pangestureerecognizer
属性)。但在这种情况下,它是视图功能的一部分,因此视图控制手势识别器是有意义的

// **** other Code ****
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];

panGesture.delegate = self;
[dragView addGestureRecognizer:panGesture];
[panGesture release];
}

- (void)panGesture:(UIPanGestureRecognizer *)gestureRecognizer 
{
    CGPoint location = [gestureRecognizer locationInView:parentView]; // The view the of the drag item is in
    gestureRecognizer.view.center = location;
}

一般来说,它通常是关于意图是什么以及谁应该在语义上负责处理动作。因此,在您的情况下,我会将
uipangestrerecognizer
添加到superview中,并让它管理自己的子视图。

CoCoCoaNetics有一个例子。他们讨论了3种不同的方法,因此值得一看。