好吧,所以我总共有5个自定义图像。 下面是我需要将每个图像设置为的值:
Image1 = 1
Image2 = 2
Image3 = 3
Image4 = 4
Image5 = 5
我需要为这些分配值,因为我想让xcode随机地将它们放在视图上,直到它达到50的值。所以我假设我需要某种循环来累加值直到达到50?
如何为这些图像赋值,因为它在尝试为UIImage分配int值时会显示警告。另外,在旁边注意我会使用什么方法将图像随机放置在视图上而不重叠?
感谢您的帮助!
答案 0 :(得分:3)
您的应用会将UIImageView
而非UIImage
放置在视图上。与所有UIView
子类一样,UIImageView
具有NSInteger
tag
属性,但如果我正确理解了问题,我认为您也不需要。
// add count randomly selected images to random positions on self.view
// (assumes self is a kind of UIViewController)
- (void)placeRandomImages:(NSInteger)count {
for (NSInteger i=0; i<count; ++i) {
UIImage *image = [self randomImage];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = [self randomFrameForImage:image];
[self.view addSubview:imageView];
// add a tag here, if you want, but I'm not sure what for
// imageView.tag = i;
}
}
// answer a random image from the app's bundle
// assumes the images are named image-x where x = 0..4
- (UIImage *)randomImage {
NSInteger imageNumber = arc4random() % 5;
NSString *imageName = [NSString stringWithFormat:@"image-%d", imageNumber];
return [UIImage imageNamed:imageName];
}
// answer a random position for the passed image, keeping it inside the view bounds
- (CGRect)randomFrameForImage:(UIImage *)image {
CGFloat imageWidth = image.width;
CGFloat imageHeight = image.height;
CGFloat maxX = CGRectGetMaxX(self.view.bounds) - imageWidth;
CGFloat maxY = CGRectGetMaxY(self.view.bounds) - imageHeight;
// random location, but always inside my view bounds
CGFloat x = arc4random() % (NSInteger)maxX;
CGFloat y = arc4random() % (NSInteger)maxY;
return CGRectMake(x,y,imageWidth,imageHeight);
}
答案 1 :(得分:2)
如果想要分配任意整数值,我会在UIImageView上使用tag属性。
NSInteger currentTag = 50;
while (currentTag > 0) {
UIImageView *imageView = [UIImageView alloc initWithImage:image];
imageView.tag = currentTag;
[self.view addSubView:imageView];
currentTag--;
}
答案 2 :(得分:0)
将图像放入NSArray,然后从NSHipster:
如何从NSArray中选择随机元素
使用arc4random_uniform(3)生成非空数组范围内的随机数。
if ([array count] > 0) {
id obj = array[arc4random_uniform([array count])];
}