簡體   English   中英

在init之后調用viewDidLoad

[英]viewDidLoad get called after init

我的主ViewController嵌入在navigation controller ,在我的ViewController我有CollectionView當我點擊custom collectionViewCell它使用push segue進入下一個View Controller ,在我的第二個View Controller我有UIImage屬性。

當我點擊Collection ViewCell時,我正在實現以下代碼

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Why did you called me?");
    DetailViewViewController *dvc = [[DetailViewViewController alloc] init];

    ALAsset *asset = self.assets[indexPath.row];
    ALAssetRepresentation *defaultRep = [asset defaultRepresentation];
    UIImage *image = [UIImage imageWithCGImage:[defaultRep fullScreenImage] scale:[defaultRep scale] orientation:0];

    [dvc initWithImage:image];

}

initWithImage方法

-(id) initWithImage:(UIImage *)imageName {
    self = [super init];
    NSLog(@"inithWithImage Called");

    self.image = imageName;

    return self;
}

問題 :問題是在viewDidLoad之前調用initWithImage 在initWithImage方法中,我將我的屬性UIImage設置為等於image 但是當我檢查viewDidLoad我的屬性UIImage等於null

我該如何解決這個問題?

您以錯誤的方式初始化DetailViewViewController 嘗試:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{
    ALAsset *asset = self.assets[indexPath.row];
    ALAssetRepresentation *defaultRep = [asset defaultRepresentation];

    UIImage *image = [UIImage imageWithCGImage:[defaultRep fullScreenImage] 
                                         scale:[defaultRep scale] 
                                   orientation:0];

    DetailViewViewController *dvc = [[DetailViewViewController alloc] initWithImage:image];

    ...
}

圖像需要是segue使用的DetailViewController實例的屬性,請查看“准備segue”

問題在於,盡管您正在使用segues,但您手動分配/初始化控制器並設置其屬性(當然這與將要呈現的實例完全不同)。

這里這里

只需在DetailViewViewController中聲明一個變量,並在分配相同實例時使用Image pathstring / image name進行初始化。 在使用pathstring / image名稱的DetailViewViewController的viewdidload中,將其設置為imageview組件。

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Why did you called me?");
    DetailViewViewController *dvc = [[DetailViewViewController alloc] init];

    //get the path of image
    ....
    ....
    dvc.variablename = imagepath / imagename
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM