以编程方式在UIView中添加UIScrollView

8

我有一个问题,如何在UIView中添加UIScrollView,使得UIScrollView能够正常工作。

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, container.frame.size.width/2, container.frame.size.height/2)];
scroll.pagingEnabled = YES;
scroll.scrollEnabled = YES;
[scroll setBackgroundColor:[UIColor redColor]];
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++)
{
    CGFloat xOrigin = i * container.frame.size.width/2;
    UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, container.frame.size.width, container.frame.size.height)];
    awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
    [scroll addSubview:awesomeView];
    [awesomeView release];
}
scroll.contentSize = CGSizeMake(container.frame.size.width/2 * numberOfViews, container.frame.size.height);
[container addSubview:scroll];

上述代码来自教程:http://idevzilla.com/2010/09/16/uiscrollview-a-really-simple-tutorial/,但是对我不起作用。 编辑:

如果您设置了一个滚动视图,但它没有工作,请确保您的滚动视图没有与另一个UIView重叠。这就是我的问题。 问题已解决!


你看不到红色的滚动视图吗? - Ishank
1
我看到了第一个UIView屏幕,颜色为red:0.5/i。 - piotr_ch
猜测,您的awesomeView比滚动视图本身更宽且更高。这意味着滚动视图正在被添加,请尝试增加滚动视图的框架和内容大小。 - Ishank
我认为你的xOrigin计算有误,awesomeView必须重叠。 - Bonnie
你可以将你的解决方案发布为答案并接受它。 - Daniel
显示剩余2条评论
3个回答

2
您可以使用以下代码在您的视图上添加UIScrollView:-
步骤1:
Delegate "UIScrollViewDelegate" to your ViewController.h

for example:
  @interface yourViewController:UIViewController<UIScrollViewDelegate> 

第二步:

//create you UIScrollView
UIScrollView  *MyScrollVw= [[UIScrollView alloc]initWithFrame:CGRectMake(0 ,0 ,320 ,480)]; 
MyScrollVw.delegate= self;
[MyScrollVw setShowsHorizontalScrollIndicator:NO];
[MyScrollVw setShowsVerticalScrollIndicator:YES];
MyScrollVw.scrollEnabled= YES;
MyScrollVw.userInteractionEnabled= YES;
[yourView addSubview:MyScrollVw];
MyScrollVw.contentSize= CGSizeMake(320 ,1500);//(width,height)

第三步:
你需要在ViewController.m中实现scrollView的代理。
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
   return imgView;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
   NSLog(@"Did end decelerating");
   //do your code here
}   
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
   NSLog(@"Did scroll");
   //do your code here
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"Did end dragging");
   //do your code here
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    NSLog(@"Did begin decelerating");
   //do your code here
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
   NSLog(@"Did begin dragging");
   //do your code here
}

1
你的。
scroll.contentSize = CGSizeMake(container.frame.size.width * numberOfViews, container.frame.size.height);

1
[container addSubview:scroll];

在你的 for 循环之前添加这行代码。

这没有帮助。我可以看到scrollview及其内容,但我无法滑动。 - piotr_ch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接