2016-05-12 3 views
-1

私はObjective-C初心者です。 setupViewメソッドでaddSubviewを使用してイメージを表示すると、これは機能しません。addSubviewは機能しません

 
    h. 


    @interface CollectionViewController : UICollectionViewController 

    @end 

    @interface MyCell : UICollectionViewCell 

    @end 

 
    m. 


    @interface MyCell() 

    @end 

    @implementation MyCell 

    - (instancetype)initWithFrame:(CGRect)frame { 
      self = [super initWithFrame:frame]; 
     if (self) [self setupView]; 
      return self; 

     } 

    - (id)initWithCoder:(NSCoder *)aDecoder 
    { 
     self = [super initWithCoder:aDecoder]; 
     if (self) [self setupView]; 
     return self; 
    } 

    -(UIImageView *)myImageView { 

     UIImageView *imageView = [UIImageView new]; 
     imageView.image = [UIImage imageNamed:@"photo.jpg"]; 
     imageView.contentMode = UIViewContentModeScaleAspectFill; 
     imageView.layer.masksToBounds = true; 
     return imageView; 

    } 

    -(void)setupView { 

     self.backgroundColor = [UIColor whiteColor]; 

     [self addSubview:self.myImageView]; 

    } 

    @end 

enter image description here

+0

画像に制約やフレームを付ける必要があります。現在は{0,0}サイズなので見えません – Shubhank

答えて

1

あり潜在的な問題の多くがありますが、最も可能性の高いImageViewのフレームが正しくありません。

UIImage *image = [UIImage imageNamed:@"photo.jpg"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
+0

ありがとうございました、今は動作しています)しかし、どうしてこんな感じですか? UIImageView * imageView = [UIImageView new]; imageView.image = [UIImage imageNamed:@ "photo.jpg"]; は動作しませんか? –

+0

'[UIImageView new]'はサイズがゼロのフレームを含む画像ビューを作成するためです。画像を設定しても、フレームサイズは変わりません。あるいは、イメージを設定した後に '[imageView sizeToFit]'を追加しても問題ありませんでした。 – EricS

+0

実際には、この亜種も気に入っています。説明ありがとう –

関連する問題