Ios addSubview不';行不通

Ios addSubview不';行不通,ios,objective-c,Ios,Objective C,我是Objective-C的初学者。当我在方法setupView中使用addSubview查看图像时,这不起作用 h. @interface CollectionViewController : UICollectionViewController @end @interface MyCell : UICollectionViewCell @end H @接口CollectionViewController:UICollectionViewContr

我是Objective-C的初学者。当我在方法setupView中使用addSubview查看图像时,这不起作用

h. @interface CollectionViewController : UICollectionViewController @end @interface MyCell : UICollectionViewCell @end H @接口CollectionViewController:UICollectionViewController @结束 @接口MyCell:UICollectionViewCell @结束 及

M @接口MyCell() @结束 @实现迈塞尔 -(instancetype)initWithFrame:(CGRect)frame{ self=[super initWithFrame:frame]; if(self)[自设置视图]; 回归自我; } -(id)initWithCoder:(NSCoder*)aDecoder { self=[super initWithCoder:aDecoder]; if(self)[自设置视图]; 回归自我; } -(UIImageView*)myImageView{ UIImageView*imageView=[UIImageView新建]; imageView.image=[UIImage ImageName:@“photo.jpg”]; imageView.contentMode=UIViewContentModeScaleAspectFill; imageView.layer.masksToBounds=true; 返回图像视图; } -(无效)设置视图{ self.backgroundColor=[UIColor whiteColor]; [self addSubview:self.myImageView]; } @结束
存在许多潜在问题,但最有可能的是imageView的框架不正确。尝试使用创建它

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

您需要为图像提供约束或帧。目前它是{0,0}大小,因此无法看到(谢谢你,现在它正在工作)但为什么像这样UIImageView*imageView=[UIImageView new];imageView.image=[UIImage ImageName:@“photo.jpg”];不起作用?因为
[UIImageView new]
创建的图像视图的边框大小为零。设置图像不会更改帧大小。或者,您可以在设置图像后添加
[imageView sizeToFit]
,这样也可以工作。实际上,这种变体也可以工作。谢谢你的解释
UIImage *image = [UIImage imageNamed:@"photo.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];