如何滚动到对象的中心位置

时间:2014-09-28 16:46:33

标签: ios objective-c uiscrollview uikit

嗨我用基本UIKit的东西制作一个简单的游戏,其中有一个对象在屏幕上弹出。

我正在努力使每次弹出对象时屏幕将滚动到对象并将其置于屏幕中心。基本上我有一个UIView,其中包含弹出的对象,而UIViewUIScrollView的子视图。所有这些都是我self.view ViewController的子视图。我正在使用UIScrollview滚动子视图的内容及其中的对象。我不确定UIScrollView是否是我想要做的理想选择,但我正在寻找一种方法来滚动对象的位置并将其置于设备中间。理想情况下是动画。

如果有人知道某种方法,或者某种方法可以帮助我,那将是非常棒的。提前致谢:D

更新: 除了在彼此之间添加视图之外,我没有太多关于此的代码:

self.world =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, currentDeviceWidth*4, currentDeviceHeight*2.2)];
self.world.backgroundColor = [UIColor blueColor];

_scrollView = [[UIScrollView alloc] initWithFrame:[[self view] bounds]];
[_scrollView setContentSize:self.world.frame.size];

[_scrollView addSubview:self.world];
[[self view] addSubview:_scrollView];

但下面是我想要完成的简单图像。箭头只是可能的滚动方向的表示。

Apple对象位于屏幕的一侧注意:apple对象是self.world的子视图,self.world是scrollview的子视图

apple object is off the side of the screen Note: apple object is a subview of self.world and self.world is a subview of scrollview

完成外观是现在滚动视图将self.world滚动到苹果对象位于屏幕中心的位置

The finish look is where now the scrollview has scroll self.world to where the apple object is in the center of the screen

只是希望基本上实现用户如何手动将对象滚动到中心,而不是使用用户的触摸自动完成。

2 个答案:

答案 0 :(得分:2)

我认为您可能需要contentOffset这是UIScrollView的属性。此属性控制contentView的位置。
现在让我们说,你的苹果在self.world的中心,然后动画把它放在中间是这样的:

    [UIView animateWithDuration: 0.5//you can put any float as you want
                     animations:^{self.world.contentOffset = CGPointMake((_scrollview.frame.size.width - self.world.frame.size.width) / 2, (_scrollview.frame.size.height - self.world.frame.size.height) / 2);
                    }];

如果您将苹果放在任何其他位置,您应自行计算位置,并将contentOffset设置为正确位置。我认为除了中心之外的任何位置都很复杂,你的计算应该包含苹果在self.world视图中的位置。

答案 1 :(得分:0)

你试过吗

[_scrollView scrollRectToVisible:newView.frame animated:(BOOL)animated]

您尝试做的事情可能很棘手的是定位视图,使它们始终位于_scroll视图的坐标系内,例如: x> =视图的中间& y> =视图的中间。