【发布时间】:2016-04-21 00:02:17
【问题描述】:
我有一个视图的子视图 我希望用户能够仅左右滚动此视图。 但是当向上或向下滚动时,我希望这个视图保持在我不希望它移动的位置。 我该怎么做?
我正在使用 iOS iphone 应用程序的 Objective c 进行编码。
谢谢
【问题讨论】:
标签: ios objective-c uiscrollview subview
我有一个视图的子视图 我希望用户能够仅左右滚动此视图。 但是当向上或向下滚动时,我希望这个视图保持在我不希望它移动的位置。 我该怎么做?
我正在使用 iOS iphone 应用程序的 Objective c 进行编码。
谢谢
【问题讨论】:
标签: ios objective-c uiscrollview subview
您可以使用UIScrollView 并设置contentSize 属性,使其height 与您视图的height 相同。
【讨论】:
创建 panRecognizer
UIPanGestureRecognizer *panRecognizer;
panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(wasDragged:)];
[[self subview] addGestureRecognizer:panRecognizer];
2.创建wasDragged方法
- (void)wasDragged:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
CGRect recognizerFrame = recognizer.view.frame;
recognizerFrame.origin.x += translation.x;
// Check if UIImageView is completely inside its superView
if (CGRectContainsRect(self.view.bounds, recognizerFrame)) {
recognizer.view.frame = recognizerFrame;
}
// Else check if UIImageView is vertically and/or horizontally outside of its
// superView. If yes, then set UImageView's frame accordingly.
// This is required so that when user pans rapidly then it provides smooth translation.
else {
// Check vertically
if (recognizerFrame.origin.y < self.view.bounds.origin.y) {
recognizerFrame.origin.y = 0;
}
else if (recognizerFrame.origin.y + recognizerFrame.size.height > self.view.bounds.size.height) {
recognizerFrame.origin.y = self.view.bounds.size.height - recognizerFrame.size.height;
}
// Check horizantally
if (recognizerFrame.origin.x < self.view.bounds.origin.x) {
recognizerFrame.origin.x = 0;
}
else if (recognizerFrame.origin.x + recognizerFrame.size.width > self.view.bounds.size.width) {
recognizerFrame.origin.x = self.view.bounds.size.width - recognizerFrame.size.width;
}
}
// Reset translation so that on next pan recognition
// we get correct translation value
[recognizer setTranslation:CGPointZero inView:self.view];
}
【讨论】: