【发布时间】:2011-12-13 19:20:04
【问题描述】:
我正在玩一个简单的测试应用程序,它只循环 10 张图像并将每张图像显示到视图中。用户单击按钮后将显示下一个图像。我遇到的问题是视图永远不会出现(图像或按钮)。当我取出按钮按下子句时,代码运行并显示最后一个图像。 continueRunningScript 最初是 YES。
@interface ViewController : UIViewController <UIAlertViewDelegate>
{
BOOL continueRunningScript;
UIButton *wrongButton;
UIImageView *imageView;
}
// ...
@end
@implementation ViewController
// ...
- (void) xxx {
for (int i = 0; i<10; i++) {
while (continueRunningScript == NO) {
// Stay here until button is pressed.
}
UIImage *testImg = ... // code to load the image at index i
imageView = [[UIImageView alloc] initWithImage: testImg];
[self.view addSubview:imageView];
wrongButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[wrongButton addTarget:self
action:@selector(incorrectResultButtonPress:)
forControlEvents:UIControlEventTouchUpInside];
[wrongButton setTitle:@"Wrong Result?" forState:UIControlStateNormal];
wrongButton.frame = CGRectMake(80.0, 310.0, 160.0, 40.0);
[self.view addSubview:wrongButton];
continueRunningScript = NO;
[testImg release];
}
[imageView release];
[wrongButton release];
}
// button press handling...
// UIAlertViewDelegate
- (void) alertView: (UIAlertView *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex {
// The user clicked one of the Yes/No buttons
if (buttonIndex == 0) // Yes
{
UIAlertView *thankyouAlert = [[UIAlertView alloc] initWithTitle:@"Thank You"
message:@"Thanks for the feedback!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[thankyouAlert show];
// Call performSelector delegate method of NSObject to call class method dismissAlertView
[self performSelector:@selector(dismissAlertView:) withObject:thankyouAlert afterDelay:2];
[thankyouAlert release];
[wrongButton removeFromSuperview];
continueRunningScript = YES;
}
}
// ...
@end
【问题讨论】:
-
这是因为您在循环中重新分配了相同的
imageView引用。当您完成循环后,它将始终指向最后一个对象。 -
以后发帖前,请先检查一下你的代码格式,不过我已经给你修好了。
-
但是为什么在循环的第一次迭代中 i=0 时视图没有显示任何内容?
-
再次查看您的代码,尝试更改每个图像的框架,看起来它只是将图像放在彼此之上。
标签: iphone objective-c xcode uiimageview uibutton