简体   繁体   English

从子类向UIView添加UIImageView

[英]Add UIImageView to UIView from subclass

I created a custom class called Slot and it is a subclass of UIView. 我创建了一个名为Slot的自定义类,它是UIView的子类。 In the slot class, the following function is called: 在插槽类中,调用以下函数:

- (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;
}

What happens is an Item (another custom class, subclass of NSObject) is passed to the Slot a UIImageView is created from the item from a string to an image in the bundle and it is added to the subview. 发生的情况是将一个Item(另一个自定义类,NSObject的子类)传递给Slot,并从该项目创建了一个UIImageView(从字符串到包中的图像),并将其添加到了子视图中。 However, the image isn't showing. 但是,该图像没有显示。 The Success message is showing so I know its getting in there. 显示成功消息,因此我知道它进入了那里。 Is there another way to add a subview from the subclass or am I just doing it all wrong? 还有另一种方法可以从子类添加子视图吗,还是我做错了所有事情?

UIImage *image = [[UIImage alloc] initWithContentsOfFile:item.imageName];

This is not the correct way to instantiate an image that you have in the bundle. 这不是实例化捆绑软件中映像的正确方法。 You can either use imageNamed: like this, 您可以使用imageNamed:这样,

UIImage *image = [UIImage imageNamed:item.imageName];

Or, you can get the image with initWithContentsOfFile like this, 或者,您可以使用initWithContentsOfFile这样获得图像,

NSString *imagePath = [[NSBundle mainBundle] pathForResource:item.imageName ofType:@"JPG"]; // replace JPG with whatever is appropriate for your image.
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

imageNamed: will cache the images, the other way doesn't. imageNamed:将缓存图像,反之则不。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM