如何以编程方式滚动UIScrollVIew

时间:2012-08-28 14:57:12

标签: objective-c

我想滚动UIScrollView(水平)。但是当按下按钮时,它会进入滚动视图的最左侧。我想滚动它3,4像素,当我再次按它时滚动另一个3,4像素

- (IBAction)leftScroll:(id)sender
{
    CGPoint pt;
    pt.x = 1;
    pt.y = 0;
    UIScrollView *sv = (UIScrollView *)[self.view viewWithTag:5];
    [sv setContentOffset:pt animated:YES];         
}

提前感谢您的回答

4 个答案:

答案 0 :(得分:18)

尝试并手动设置新位置。

<强>目标c

  float width = CGRectGetWidth(scrollView.frame);
  float height = CGRectGetHeight(scrollView.frame);
  float newPosition = scrollView.contentOffset.x+width; 
  CGRect toVisible = CGRectMake(newPosition, 0, width, height);

 [scrollView scrollRectToVisible:toVisible animated:YES];

Swift 4

let scrollView = UIScrollView()
let width: CGFloat = scrollView.frame.size.width
let height: CGFloat = scrollView.frame.size.height
let newPosition: CGFloat = scrollView.contentOffset.x + width
let toVisible: CGRect = CGRect(x: newPosition, y: 0, width: width,   height: height)

scrollView.scrollRectToVisible(toVisible, animated: true)

答案 1 :(得分:5)

您可以使用[scrollView setContentOffset:CGPointMake(x, y) animated:YES];方法。如果您的scrollView水平滚动,则需要相应地设置x值,否则为y值。

答案 2 :(得分:3)

您可以使用Obj-C

中的以下内容滚动到滚动视图中的某个点
[scrollView setContentOffset:CGPointMake(x, y) animated:YES];

或Swift

scrollView.contentOffset = CGPoint(x: x, y: y)

要使用UIScrollView进行幻灯片放映,您可以在滚动视图中排列所有图像,设置重复计时器,然后设置-setContentOffset:animated:当计时器触发时。

答案 3 :(得分:0)

UIButton *locatorbutton_frame=(UIButton *)[scrollviewoutlet viewWithTag:numberglobal];
float width = scrollviewoutlet.frame.size.width;
float height = scrollviewoutlet.frame.size.height;
float newPosition = scrollviewoutlet.contentOffset.x-locatorbutton_frame.frame.size.width;//+width;
CGRect toVisible = CGRectMake(newPosition, 0, width, height);

[scrollviewoutlet scrollRectToVisible:toVisible animated:YES];

我发现它工作正常locatorbutton_frame是我添加到滚动视图的按钮。