有史以来最奇怪的是,UIButton @selector检测到右键,做错了'else_if'?

Sco*_*ott 3 iphone objective-c selector uibutton

所以我用这个循环动态创建3个UIButton(现在):

NSMutableArray *sites = [[NSMutableArray alloc] init];

     NSString *one = @"Constution Center";
     NSString *two = @"Franklin Court";
     NSString *three = @"Presidents House";

     [sites addObject: one];
     [one release];

     [sites addObject: two];
     [two release];

     [sites addObject: three];
     [three release];

     NSString *element;
     int j = 0;
     for (element in sites)
     {
         UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

         //setframe (where on screen)
         //separation is 15px past the width (45-30)
         button.frame = CGRectMake(a, b + (j*45), c, d);

         [button setTitle:element forState:UIControlStateNormal];

         button.backgroundColor = [SiteOneController myColor1];

        [button addTarget:self action:@selector(showCCView:)
        forControlEvents:UIControlEventTouchUpInside];
         [button setTag:j];

         [self.view addSubview: button];
         j++;
     }
Run Code Online (Sandbox Code Playgroud)

@Selector方法在这里:

- (void) showCCView:(id) sender {

    UIButton *button = (UIButton *)sender;
    int whichButton = button.tag;
    NSString* myNewString = [NSString stringWithFormat:@"%d", whichButton];
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    self.view.backgroundColor = [UIColor whiteColor];

    UINavigationBar *cc = [SiteOneController myNavBar1:@"Constitution Center Content"];
    UINavigationBar *fc = [SiteOneController myNavBar1:@"Franklin Court Content"];
    UINavigationBar *ph = [SiteOneController myNavBar1:@"Presidents House Content"];

    if (whichButton = 0) 
    {
        NSLog(myNewString);
        [self.view addSubview:cc];
    }
    else if (whichButton = 1) 
    {
        NSLog(myNewString);
        [self.view addSubview:fc];
    }
    else if (whichButton = 2) 
    {
        NSLog(myNewString);
        [self.view addSubview:ph];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,它正在向NSLog打印正确的按钮标签,如方法所示,但是每个单按钮都显示一个导航栏,其中"Franklin Court"作为标题,每个单一,即使我点击按钮0,它说"按钮0单击"在控制台中,但仍然执行else if(whichButton = 1)代码.

我在这里错过了什么吗?

zne*_*eak 7

您在条件中使用=运算符而不是==运算符,这使得赋值而不是比较.

由于赋值的返回值是赋值,因此首先whichButton变为0,并且计算结果为false,然后whichButton变为1并且计算结果为true,无论您做什么,最终都会使用Franklin Court选项.

  • @dreamlax:这是对的.我们应该称这种比较风格为"尤达条件". (18认同)
  • @sbooth:这就是我推广仅在其分支结构中接受布尔表达式的语言的原因. (3认同)
  • `constant == variable`的问题在于它读得不太好.这就像说"如果蓝色是天空"或"如果高大就是男人".问题是我认为Xcode的默认编译器设置会因为`if(self = [super init])`习惯用法而禁用赋值警告. (3认同)