随机化UIImageView的图像

Eri*_*ric 3 objective-c uiimageview ios

[self randomizeBanner];viewDidLoad;主线程中调用,NSTimer其中我将UIImageView的图像随机化为横幅广告.

@property (strong, nonatomic) UIImageView *bannerBackgroundImage;
Run Code Online (Sandbox Code Playgroud)

...

- (void)randomizeBanner {

    NSInteger randomNum = arc4random_uniform(5);

    NSArray *arrayOfImages = [[NSArray alloc]initWithObjects:
                              [UIImage imageNamed:@""],
                              [UIImage imageNamed:@""],
                              [UIImage imageNamed:@""],
                              [UIImage imageNamed:@""],
                              [UIImage imageNamed:@""],
                              nil];

   [_bannerBackgroundImage setImage:[arrayOfImages objectAtIndex:randomNum]];

}
Run Code Online (Sandbox Code Playgroud)

随机化UIImageView图像的最佳方法是什么?

Piy*_*rma 6

实现同样目的的一种方法是:

假设你的图像序列中image1.png - image5.png ,然后

UIImage * randomImage = [ UIImage imageNamed:[ NSString stringWithFormat:@"image%u.png", 1+arc4random_uniform(4)]] ;
[_bannerBackgroundImage setImage:randomImage];
Run Code Online (Sandbox Code Playgroud)

在每次调用函数的方法中,一次又一次地创建数组.使用我的方法,将无需管理您只需按顺序管理图像名称所需的图像数组.