I want to loop through an array of images and display each image one by one on the click of a single button.
我想循环浏览一系列图像,并通过单击一个按钮逐个显示每个图像。
Here is my code.
这是我的代码。
This is in the viewDidLoad method:
这是在viewDidLoad方法中:
arrayImg = [[NSArray alloc]initWithObjects:
[UIImage imageNamed:@"samsung_logo_small.jpg"],
[UIImage imageNamed:@"Small_logo_splash.png"],
[UIImage imageNamed:@"Red_logos_small.png"],
[UIImage imageNamed:@"li-logo-small-drshdw.gif"],
nil];
Here is my button in which I am looping through the images
这是我的按钮,我循环浏览图像
- (IBAction)btn:(id)sender {
for (int i = 0 ; i < [arrayImg count]; i++) {
[img setImage:[arrayImg objectAtIndex:i]];
}
}
The problem is that it is only showing the last image, not all of the images.
问题是它只显示最后一张图像,而不是所有图像。
What I am doing wrong here?
我在这做错了什么?
I found 2 questions like this on but could not find the answer.
我发现了2个这样的问题,但找不到答案。
3
Add following to YourClass.m
file:
将以下内容添加到YourClass.m文件中:
@interface YourClass() {
int variableName;
}
@end
in viewDidLoad
initialize variableName to 0
.
在viewDidLoad中将variableName初始化为0。
- (IBAction)btn:(id)sender
{
if (variableName == arrayImg.count)
{
variableName = 0;
}
[img setImage:[arrayImg objectAtIndex:classVariable]];
variableName++
}
2
If you want to show one image at a time then why loop? You can do it like this:
如果你想一次显示一个图像,那么为什么要循环?你可以这样做:
static int index;
- (IBAction)btn:(id)sender {
[img setImage:[arrayImg objectAtIndex:index]];
index = index == arrayImg.count - 1 ? 0 : index + 1;
}
1
In your viewDidLoad
, add one more line:
在viewDidLoad中,再添加一行:
[buttonName setTag:0];
Here change in btn event:
这里改变了btn事件:
- (IBAction)btn:(UIButton *)sender {
[img setImage: [arrayImg objectAtIndex: [sender tag]]];
[sender setTag: [sender tag]+1];
if ([sender tag] > [arrayImg count]) {
[sender setTag: 0];
}
}
This will help you in memory management as well, because here no other extra flag variable required to hold your integer value, whereas your UIButton
object only will hold.
这也可以帮助你进行内存管理,因为这里没有其他额外的标志变量来保存你的整数值,而你的UIButton对象只能保存。
Hope this will help you to achieve your requirement.
希望这能帮助您实现您的要求。
0
From what I can tell, you're looping through all of the images on a single click.
据我所知,您只需单击一下即可遍历所有图像。
A better approach might be to display an image after a click but instead of looping just increment a variable that represents your index value by 1. This way after each click the next image is displayed.
更好的方法可能是在单击后显示图像,而不是循环只是将表示索引值的变量增加1.这样每次单击后,将显示下一个图像。
The other approach would be to use a timer.
另一种方法是使用计时器。
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(displayNextImage:)
userInfo:nil
repeats:YES];
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2014/12/13/3c4f38dcb565cfc62c473a9f82878138.html。