Lee Sugden Lee Sugden - 6 months ago 8
iOS Question

Updating UILabel from another View Controller

Hi i am kind of stuck at the moment as to sending UILabel data across from one view controller to another coming from a collection view cell. Here is my current code of which i get no errors? May seem obvious to someone who knows what they are doing but do i need to somehow declare on the second view controller that i am setting the UILabel from another VC?

Here is my current code as follows:

GroupsViewController.m

#import "GroupsViewController.h"
#import "GroupsHomeViewController.h"
#import "CustomCell.h"

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:@"GroupsHomeSegue" sender:indexPath];
}

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

if ([segue.identifier isEqualToString:@"GroupsHomeSegue"])
{
NSIndexPath* indexPath = [[self.GroupsCollectionView indexPathsForSelectedItems]firstObject];
if(indexPath !=nil)
{
NSString *selectedImage = arrayOfImages [indexPath.item]; //collect image
GroupsHomeViewController *groupsHomeVC = segue.destinationViewController; //set D.V.C
groupsHomeVC.logoImage = [UIImage imageNamed: selectedImage]; //set image
groupsHomeVC.groupLabel.text = arrayOfDescriptions[indexPath.item ]; //set text

}
}
}


GroupsHomeViewController.h

@interface GroupsHomeViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UIImageView *logoImageView;
@property (strong, nonatomic) UIImage *logoImage;
@property (strong, nonatomic) IBOutlet UILabel *groupLabel;
@end


GroupsHomeViewController.m

#import "GroupsHomeViewController.h"

@interface GroupsHomeViewController ()

@end

@implementation GroupsHomeViewController

-(void)viewDidLoad{
[super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
self.logoImageView.image = self.logoImage;
}


Many Thanks in advance for your time and patience.

Answer

Because At this time, the GroupsHomeViewController is not loaded in the memory yet, that's why you are facing this issue. Instead of directly passing value to UILabel, try passing text using NSString. Declare

@property (strong,nonatomic) NSString *valueToPass;

in GroupsHomeViewController . Then pass value to string using below code

NSString *selectedImage = arrayOfImages [indexPath.item]; //collect image
GroupsHomeViewController *groupsHomeVC = segue.destinationViewController; //set D.V.C
groupsHomeVC.logoImage = [UIImage imageNamed: selectedImage]; //set image
// pass string to next viewController's NSString object.            
groupsHomeVC.valueToPass = arrayOfDescriptions[indexPath.item ]; 

Then in viewDidLoad of GroupsHomeViewController ,set string on UILabel like this self.groupLabel.text=self.valueToPass. Try doing this.

Comments