我正在做一個小測驗式的應用程序,但我有幾個問題。隨機化對象位置
我隨意使用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