Ios 将UIImageView从子类添加到UIView
我创建了一个名为Slot的自定义类,它是UIView的一个子类。在slot类中,调用以下函数:Ios 将UIImageView从子类添加到UIView,ios,objective-c,uiview,uiimageview,Ios,Objective C,Uiview,Uiimageview,我创建了一个名为Slot的自定义类,它是UIView的一个子类。在slot类中,调用以下函数: - (NSString*)assignItem:(Item*)item { NSString *message; if (item.slotSize + currentCapacity > slotSize) { message = @"Sorry this item will not fit."; } else { //uiimageview stu
- (NSString*)assignItem:(Item*)item {
NSString *message;
if (item.slotSize + currentCapacity > slotSize) {
message = @"Sorry this item will not fit.";
} else {
//uiimageview stuff
UIImage *image = [[UIImage alloc] initWithContentsOfFile:item.imageName];
UIImageView *iv = [[UIImageView alloc] initWithImage:image];
[self addSubview:iv];
[items addObject:item];
currentCapacity = currentCapacity + item.slotSize;
message = @"Success";
}
NSLog(@"%@",message);
return message;
}
所发生的事情是将一个项(另一个自定义类,NSObject的子类)传递到插槽,然后从该项创建UIImageView,从字符串到捆绑包中的图像,并将其添加到子视图中。然而,图像没有显示出来。成功的信息正在显示,所以我知道它正在进入。是否有其他方法从子类添加子视图,或者我只是做错了
UIImage *image = [[UIImage alloc] initWithContentsOfFile:item.imageName];
这不是实例化捆绑包中的映像的正确方法。您可以使用ImageName:这样
UIImage *image = [UIImage imageNamed:item.imageName];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:item.imageName ofType:@"JPG"]; // replace JPG with whatever is appropriate for your image.
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
或者,您可以使用initWithContentsOfFile获取图像,如下所示
UIImage *image = [UIImage imageNamed:item.imageName];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:item.imageName ofType:@"JPG"]; // replace JPG with whatever is appropriate for your image.
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
ImageName:将缓存图像,另一种方式不会。是否使用情节提要?如果是,您是否在其中放置了一个空白UIImageView?如果这样做,您甚至可能不必将其添加为子视图。根据这个逻辑,用你的图像初始化它,或者隐藏它/当你的逻辑要求它不应该这样做时,什么也不做。如果你在分配图像后设置断点,你能看到图像被正确加载吗?哦,哇。谢谢雷姆斯。由于我是如何初始化的,因此无法加载该图像。更改为UIImage*image=[UIImage imageName:item.imageName];现在一切都很美好。谢谢是的。刚刚意识到我的错误。谢谢