简体   繁体   English

在iPhone编程中,子视图应更改其自身的框架和中心,还是超级视图应更改其框架和中心?

[英]In iPhone programming, should a subview change its own frame and center or should a superview change them?

I need the user to be able to drag a subview across the screen to change the subview's position. 我需要用户能够在屏幕上拖动子视图以更改子视图的位置。 I know that it is possible to do it either way, but is one way preferred? 我知道这两种方法都是可行的,但是一种方法更可取吗? And why? 又为什么呢?

Based purely on the concept of MVC, whatever is responsible for that view should probably handle the pan gesture recognizer. 纯粹基于MVC的概念,负责该视图的任何事物都应该处理平移手势识别器。 At least, that's what I do. 至少,我就是这么做的。 The view itself shouldn't really care or be aware that it's being moved around. 视图本身并不真正在乎或意识到它正在四处移动。

Now, for something like zooming or scrolling, that does seem relevant to the view (eg, UIScrollView has the panGestureRecognizer property). 现在,对于缩放或滚动之类的东西,它似乎与视图确实相关(例如, UIScrollView具有panGestureRecognizer属性)。 But in this case, it's part of the functionality of the view, so it makes sense for the view to control that gesture recognizer. 但是在这种情况下,它是视图功能的一部分,因此视图控制该手势识别器很有意义。

In general, it's usually about what the intent is and who should semantically be responsible for handling the action. 通常,通常是关于意图是什么以及语义上应该负责处理该操作的人员。 So, in your case, I would add the UIPanGestureRecognizer to the to the superview and let it manage its own subviews. 因此,在您的情况下,我将UIPanGestureRecognizer添加到UIPanGestureRecognizer视图中,并让它管理自己的子视图。

If you are using iOS 3.2 or higher look into UIPanGestureRecognizer. 如果您使用的是iOS 3.2或更高版本,请查看UIPanGestureRecognizer。

// **** 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;
}

This is all done from memory, but it should be something like this 这些都是通过内存完成的,但应该是这样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM