UIScrollView生成图片

时间:2013-08-02 04:49:23

标签: ios objective-c

我已经设置了一个UIScrollView并加载了图片并将其设置为等于视图,图片之间有一些偏移。有人可以解释我可能做错了吗?它显示第一张图片很好但不会让我左右滚动以查看下一张图片。我是否需要使用新的XCode手势识别器才能使其正常工作?

 - (void)viewDidLoad
    {
        [super viewDidLoad];

        int PageCount = 3;

        UIScrollView *Scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        Scroller.backgroundColor = [UIColor clearColor];
        Scroller.pagingEnabled = YES;
        Scroller.contentSize = CGSizeMake(PageCount = Scroller.bounds.size.width, Scroller.bounds.size.height);

        CGRect ViewSize = Scroller.bounds;

        UIImageView *ImgView = [[UIImageView alloc] initWithFrame:ViewSize];
        [ImgView setImage:[UIImage imageNamed:@"1.png"]];
        [Scroller addSubview:ImgView];

        ViewSize = CGRectOffset(ViewSize, Scroller.bounds.size.width, 0);

        UIImageView *ImgView2 = [[UIImageView alloc] initWithFrame:ViewSize];
        [ImgView2 setImage:[UIImage imageNamed:@"2.png"]];
        [Scroller addSubview:ImgView2];

        ViewSize = CGRectOffset(ViewSize, Scroller.bounds.size.width, 0);

        UIImageView *ImgView3 = [[UIImageView alloc] initWithFrame:ViewSize];
        [ImgView3 setImage:[UIImage imageNamed:@"3.png"]];
        [Scroller addSubview:ImgView3];

        [self.view addSubview:Scroller];

    }

    @end

2 个答案:

答案 0 :(得分:0)

您需要手动将ScrollView的contentSize设置为适合您添加的所有ImageViews的最大矩形。例如:假设您想要向右和向左滚动,并且您有4个视图,每个视图的宽度为100,并且您在x方向上的偏移量为10。然后,在将所有4个观看次数添加到scrollView后,您必须按如下所示制作contentSize:

scrollView.contentSize = CGSizeMake( 10 + (100 + 10)*4 , scrollView.contentSize.y );

这将使scrollView可滚动,您将看到所有视图。

答案 1 :(得分:0)

试试这个

int PageCount = 3;
NSMutableArray *arrImageName =[[NSMutableArray alloc]initWithObjects:@"1.png",@"2.png",@"3.png", nil];
UIScrollView *Scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
Scroller.scrollEnabled=YES;
Scroller.backgroundColor = [UIColor clearColor];
Scroller.pagingEnabled = YES;
[self.view addSubview:Scroller];
int width=Scroller.frame.size.width;
int xPos=0;
for (int i=0; i<PageCount; i++)
{
    UIImageView *ImgView = [[UIImageView alloc]initWithFrame:CGRectMake(xPos, 0, Scroller.frame.size.width, Scroller.frame.size.height)];
    [ImgView setImage:[UIImage imageNamed:[arrImageName objectAtIndex:i]]];
    [Scroller addSubview:ImgView];
    Scroller.contentSize = CGSizeMake(width, 0);
    width +=Scroller.frame.size.width;
    xPos  +=Scroller.frame.size.width;
}