如何从Parse.com随机显示图像

时间:2013-12-29 20:00:31

标签: ios objective-c random uitableview parse-platform

我想在UITableViewCell中随机显示个人资料图片。

我的表格设置为过滤方式。我在Parse上为用户设置了一个表,它还包含一个类别列和图片列。我想按类别查询(每个单元格行是一个类别,如下面的示例),并随机显示UITableViewCell中的图像。

因此表格将设置为:

A类

B类

C类

每个单元格中都有UIImageViews,我想在每个单元格中随机显示图像。

这是我尝试过的,但没有运气。

// in ViewDidLoad
self.theArray = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D", nil];

// in cellForRowAtIndexPath
cell.label.text = [self.theArray objectAtIndex:indexPath.row];

PFQuery * query = [PFUser query]; 
[query whereKey:@"category" equalTo:cell.label.text]; 
[query findObjectsInBackgroundWithBlock:(NSArray *objects, NSError error) {

    if (error)
    {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
    else
    {
        for (int i = 0; i < objects.count; i++)
        {
            self.profilePicObject = [objects objectAtIndex:i];

            int imgRandom = random() % [objects count];

            self.randomProfilePicObject = [objects objectAtIndex:imgRandom];

            self.imageFile = [self.randomProfilePicObject objectForKey:@"imageFile"];
            NSURL * imageFileURL = [[NSURL alloc] initWithString:self.imageFile.url];
            NSData * imageData = [NSData dataWithContentsOfURL:imageFileURL];
            UIImage * aImage = [[UIImage alloc] initWithData:imageData];

            cell.profilePicOne.image = aImage;
        }
    }
}];

编辑:

我修改了上面的代码,现在正在运行。修改此内容以在单元格中填写多个UIImageView的最有效方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

    for (int i = 0; i < objects.count; i++)
    {
        //self.profilePicObject = [objects objectAtIndex:i];

        int randomImgNumber = arc4random_uniform(5); // You could several many times the same picture !!!
        self.profilePicObject = [objects objectAtIndex:randomImgNumber];

        self.imageFile = [self.profilePicObject objectForKey:@"imageFile"];
        NSURL * imageFileURL = [[NSURL alloc] initWithString:self.imageFile.url];
        NSData * imageData = [NSData dataWithContentsOfURL:imageFileURL];
        UIImage * aImage = [[UIImage alloc] initWithData:imageData];

       // aImage = [objects objectAtIndex:randomImgNumber];

        cell.profilePicOne.image = aImage;
    }