如何在uiscrollview中显示当前显示的uiimage?

时间:2013-03-30 17:45:05

标签: ios uiscrollview uiimage

我有以下代码,它接受一个包含uiimage路径的nsdictionary数组,并将它们逐个添加到uiscrollview中。

- (void)displayAssets:(NSArray*)postAssets //configured for search
{
    for (UIView *v in self.scrollview.subviews) {
        [v removeFromSuperview];
    }

    CGRect workingFrame = self.scrollview.frame;
    workingFrame.origin.x = 0;

    self.scrollview.delegate = self;
    //    self.scrollview.contentInset=UIEdgeInsetsMake(10.0,0.0,10.0,0.0);

    NSString *pathOfNoImageFile = [[NSBundle mainBundle] pathForResource:@"noimage" ofType:@"png"];

    if (postAssets == nil || [postAssets count] == 0) {

        UIImage *noImage = [UIImage imageWithContentsOfFile:pathOfNoImageFile];
        UIImageView *imageview = [[UIImageView alloc] initWithImage:noImage];

        [imageview setContentMode:UIViewContentModeScaleAspectFit];
        imageview.frame = workingFrame;
        [self.scrollview addSubview:imageview];
    }
    else
    {

            //at this moment we have an actual NSArray/NSDictionarry of images that has keys etc.

            for (NSDictionary *asset in postAssets) //we have to differentiate between images and videos in future
            {

                //ASSUMING FIRST VALUE IN ASSETS IS AN Image   THIS WILL NEED REFACTORING FOR VIDEOS LATER
                NSString * assetID = [asset valueForKeyPath:@"id"];
                NSString * imageURL = [NSString stringWithFormat:@"%@post/7777/images/%@.jpg", WEB_SERVICE_BASE_URL, assetID];

                UIImage *waitingImage = [UIImage imageWithContentsOfFile:pathOfNoImageFile];
                UIImageView *imageview = [[UIImageView alloc] init];

                [imageview  setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:waitingImage];

                [imageview setContentMode:UIViewContentModeScaleAspectFit];
                imageview.frame = workingFrame;

                [self.scrollview addSubview:imageview];
                workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
            }
            [self.scrollview setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];



    }

    //    [[self tableView] reloadData];

}

我在同一个文件的另一个函数中尝试做的是获取第一个uiimage或当前显示的uiimage,但我无法这样做。 Uiscrollview似乎没有一种方法可以让我们深入到各个视图,这样我就可以获得uiimage。我看过其他的SO问题,但它们似乎很复杂。

有人可以指导我吗?我对uiscrollviews相当新。

谢谢

1 个答案:

答案 0 :(得分:0)

假设每个图像的宽度与滚动视图相同,您可以:

  1. 保留指向您添加的UIImages的指针数组,然后使用scrollview.contentOffset.x / scrollview.bounds.size.width

  2. 获取当前显示图像的索引
  3. 使用hitTest:(CGPoint)point withEvent:(UIEvent *)event作为要点调用scroller.contentOffset - 此时应该返回最上面的视图,该视图应该是您的UIImageView