我正在做一个小测验式的应用程序,但我有几个问题。随机化对象位置
我随意使用arc4random(),然后我填充3个按钮,其中一个包括一个正确的答案,另2视图从一个NSMutableArray的问题包括两个错误答案
什么,我需要做的是随机化视图中3个按钮的X坐标(位置)这是我正在使用的代码,但它给我带来问题,因为它无法正常工作nd该应用程序在调用动作时经常崩溃:
NSBundle *bundle02 = [NSBundle mainBundle];
NSString *textFilePath02 = [bundle02 pathForResource:@"possiblePositions" ofType:@"txt"];
NSString *fileContents02 = [NSString stringWithContentsOfFile:textFilePath02 encoding:NSUTF8StringEncoding error:nil];
arrayPossiblePositions = [[NSMutableArray alloc] initWithArray:[fileContents02 componentsSeparatedByString:@"\n"]];
int length02 = [arrayPossiblePositions count];
int chosen02 = arc4random() % length02;
[arrayPossiblePositions removeObjectAtIndex:chosen02];
int chosen04 = arc4random() % length02;
[arrayPossiblePositions removeObjectAtIndex:chosen04];
int chosen05 = arc4random() % length02;
if ([questionString isEqualToString:@"question1"]) {
buttonCorrect = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect newSize = CGRectMake(chosen02, 80, 130, 130);
buttonCorrect.frame = newSize;
[buttonCorrect setImage:[UIImage imageNamed:@"kncpf.png"] forState:UIControlStateNormal];
[buttonCorrect addTarget:self action:@selector(answerCorrect) forControlEvents:UIControlEventTouchUpInside];
[main addSubview:buttonCorrect];
buttonUncorrect01 = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect newSize02 = CGRectMake(chosen04, 80, 130, 130);
buttonUncorrect01.frame = newSize02;
[buttonUncorrect01 setImage:[UIImage imageNamed:@"kncpf02.png"] forState:UIControlStateNormal];
[buttonUncorrect01 addTarget:self action:@selector(answerUncorrect) forControlEvents:UIControlEventTouchUpInside];
[main addSubview:buttonUncorrect01];
buttonUncorrect02 = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect newSize034578 = CGRectMake(chosen05, 80, 130, 130);
buttonUncorrect02.frame = newSize034578;
[buttonUncorrect02 setImage:[UIImage imageNamed:@"kncpf034578.png"] forState:UIControlStateNormal];
[buttonUncorrect02 addTarget:self action:@selector(answerUncorrect) forControlEvents:UIControlEventTouchUpInside];
[main addSubview:buttonUncorrect02];
}
你能否建议我做一些不同的事情,因为我真的变得疯了?
预先感谢答案, 大卫
这听起来不错,但现在的问题是,我创建了一个带图像名称的NSMutableArray,但即使NSLog确认所有内容都正常工作,随机图像也不会显示在按钮中,并且如果添加了删除选项对象,应用程序崩溃....这是我使用的代码:http://shorttext.com/0rr3vxr9te 我该怎么办? 谢谢你 – 2010-05-11 18:39:57
检查我的补充:一个问题可能是您在创建按钮图像之前从阵列中删除对象。 NSString * laggo02 = [arrayPosizioniPossibili objectAtIndex:chosen02];可能只是创建一个指针,而不是在内存中创建一个全新的部分。 – 2010-05-11 21:35:26
[button1 setImage:[UIImage imageNamed:[imagesArray objectAtIndex:index1]] forState:UIControlStateNormal]; - 这似乎不工作正常,也许是因为它不是一个NSString,但即使我编码:NSString * stringozzo01 = [immaginiSbagliate objectAtIndex:index1];然后将其分配给随机图像,它会崩溃 你有什么建议吗? 非常感谢时间和耐心的人 – 2010-05-12 20:58:11