繁体   English   中英

从CollectionView到ViewController隔离项目信息

[英]Segue item info from CollectionView to ViewController

下午好,

当用户触摸我的CollectionView中的某个项目时,我正在尝试创建一个Segue,但是它不起作用。 首先,我从数据库中获取用户的条目(它们是图像的完整URL),然后将其显示在“收藏夹视图”中。

问题是,当我尝试发送我触摸过的那个时,它总是NULL。 我尝试了以下教程和示例,但是没有人从数据库中加载条目(还有完整的URL)。 图像被加载到“ fetchImages”中。

你能帮助我吗? 如何发送我触摸过的商品的网址?

这是我的ViewController(我的CollectionView所在的位置):

//

#import "ProfileViewController.h"
#import "CarDetailOtherViewController.h"
#import <Security/Security.h>
#import "SSKeychainQuery.h"
#import "SSKeychain.h"
#import "SBJson.h"

@interface NSURLRequest (DummyInterface)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;

+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end

@interface ProfileViewController ()

@end

@implementation ProfileViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {

    [super viewDidLoad];

    [self.view setBackgroundColor: [self colorWithHexString:@"FFFFFF"]];

    self.profileimage.layer.cornerRadius = self.profileimage.frame.size.width / 2;
    self.profileimage.clipsToBounds = YES;
    self.profileimage.layer.borderWidth = 1.0f;
    self.profileimage.layer.borderColor = [UIColor whiteColor].CGColor;

    [self fetchImages];

    // COLLECTION VIEW
    self.oneCollectionView.dataSource = self;
    self.oneCollectionView.delegate = self;
}

// MOSTRAMOS LA INFO CUANDO SE HAYA MOSTRADO EL VIEW
- (void)viewDidAppear:(BOOL)animated
{
    [self fetchJson];
}

// COLLECTION VIEW
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

// COLLECTION VIEW
-(NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
    return 1;
}

// COLLECTION VIEW
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _carImages.count;
}

/*
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";

    RecipeViewCell *cell = (RecipeViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame-2.png"]];
    cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame-selected.png"]];

    return cell;
}
*/
// COLLECTION VIEW
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *myCell = [collectionView
                                    dequeueReusableCellWithReuseIdentifier:@"MyCell"
                                    forIndexPath:indexPath];

    NSString *data = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"imagen"];
    NSURL * imageURL = [NSURL URLWithString:data];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imageData = [NSData dataWithContentsOfURL: imageURL];
        UIImage *img = [UIImage imageWithData:imageData];
        [myCell.imageview performSelectorOnMainThread:@selector(setImage:) withObject:img waitUntilDone:YES];
    });

    return myCell;
}

// PROFILE INFO
-(void)fetchJson {

    NSString *usersPassword = [SSKeychain passwordForService:@"login" account:@"account"];

    NSLog(@"usersPassword ==> %@", usersPassword);

    NSString *post =[[NSString alloc] initWithFormat:@"usersPassword=%@",usersPassword];
    //NSLog(@"PostData: %@",post);

    NSURL *url=[NSURL URLWithString:@"http://website.com/profile.php"];

    //NSData * data = [NSData dataWithContentsOfURL:url];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    //NSLog(@"Response code: %ld", (long)[response statusCode]);
    if ([response statusCode] >=200 && [response statusCode] <300)
    {
        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

        SBJsonParser *jsonParser = [SBJsonParser new];
        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];

        NSInteger stars = [(NSNumber *) [jsonData objectForKey:@"stars"] integerValue];
        self.stars.text = [NSString stringWithFormat:@"%li", (long)stars];

        NSInteger followers = [(NSNumber *) [jsonData objectForKey:@"followers"] integerValue];
        self.followers.text = [NSString stringWithFormat:@"%li", (long)followers];

        NSInteger pictures = [(NSNumber *) [jsonData objectForKey:@"photos"] integerValue];
        self.pictures.text = [NSString stringWithFormat:@"%li", (long)pictures];

        self.username.text = [NSString stringWithFormat:@"*%@", usersPassword];

        NSString *picture = [jsonData objectForKey:@"picture"];
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:picture]];
        self.profileimage.image = [UIImage imageWithData:imageData];
    }
}

-(void)fetchImages {

    self.carImages = [[NSMutableArray alloc] init];

    NSString *usersPassword = [SSKeychain passwordForService:@"login" account:@"account"];

    NSString * urlString = [NSString stringWithFormat:@"http://website.com/posts.php?usersPassword=%@",usersPassword];

    NSURL * url = [NSURL URLWithString:urlString];
    NSData * data = [NSData dataWithContentsOfURL:url];

     NSError *error;
    [_jsonArray removeAllObjects];
    _jsonArray = [NSJSONSerialization
                  JSONObjectWithData:data
                  options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
                  error:&error];

    for(int i=0;i<_jsonArray.count;i++)
    {
        NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
        NSString* imagen = [jsonObject objectForKey:@"imagen"];
        [_carImages addObject:imagen];
    }
    NSLog(@"CARIMAGES ==> %@", _carImages);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// IMAGEN
-(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"segueentry"])
    {
        NSArray *indexPaths = [self.oneCollectionView indexPathsForSelectedItems];
        CarDetailOtherViewController *destViewController = segue.destinationViewController;
        NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
        destViewController.ID = [[_jsonArray objectAtIndex:indexPath.section] valueForKey:@"imagen"];

        NSLog(@"DATA ==> %@", [[_jsonArray objectAtIndex:indexPath.section] valueForKey:@"imagen"]);
    }
}

@end

提前致谢。

它必须是而不是您的prepareforsegue中的部分

destViewController.ID = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"imagen"];

顺便说一句:您可以通过以下操作轻松获取indexpath:

NSIndexPath *selectedIndexPath = [self.collectionView indexPathForCell:sender];

您必须添加此委托方法,每次在UICollectionView中选择一个项目时,都会调用此委托。 在此代表内部执行您的segue。 作为发送者,发送您选择的indexPath。

- (void)collectionView:(UICollectionView *)collectionView 
         didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self performSegueWithIdentifier:@"segueentry" sender: indexPath];
}

然后从- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender您可以获取选定的indexPath作为逻辑发送者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM