基本Objective-C数组'for'循环辅助

时间:2011-01-22 22:15:04

标签: iphone objective-c xcode

所以继续我的挂断,我创建一个数组,将按钮传递给它并使用for循环试图将每个按钮放在视图上。我知道他们将处于相同的位置,因为他们都经历了相同的CGRectMake。但是我似乎无法在屏幕上放置任何代码,尽管它没有返回任何错误,但仍然让我难以理解为什么。

有人有什么建议吗?谢谢!

- (void)practiceMethod{

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Practice Method has begun" message:@"Alert" delegate: self cancelButtonTitle:@"Close" otherButtonTitles: nil];
 //[alert show];
 [alert release];

 float i=0;

 CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

 UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];

 UIButton *buttonOne = [[UIButton alloc] initWithFrame:applicationFrame];
 UIButton *buttonTwo = [[UIButton alloc] initWithFrame:applicationFrame];

 buttonArray = [[NSArray alloc] initWithObjects:buttonOne, buttonTwo,nil];

 for (i = 0; i > [buttonArray count]; i++) {

  UIButton *tempElement = [buttonArray objectAtIndex:i];

  tempElement.frame = CGRectMake(140, 230, 50, 50);

  [tempElement setBackgroundImage:buttonGraphic forState:UIControlStateNormal];

  [self addSubview:tempElement];
 }
}

2 个答案:

答案 0 :(得分:8)

更改

for (i = 0; i > [buttonArray count]; i++) {

for (i = 0; i < [buttonArray count]; i++) {

你就会开始运作。

PS。我建议您使用Objective-Cs for each迭代器来解决这些问题:

for( UIButton* button in buttonArray )
{ 
    // stuff with button
}

答案 1 :(得分:3)

替换:

for (i = 0; i > [buttonArray count]; i++) {
   UIButton *tempElement = [buttonArray objectAtIndex:i];
   ...

}

使用数组循环快捷语法:

for (UIButton *tempElement in buttonArray) {
    ...

}

最好将buttonWithType:与UIButton一起使用:

UIButton *buttonOne = [UIButton buttonWithType: UIButtonTypeCustom];
buttonOne.frame = applicationFrame;