iphone - 有史以来最奇怪的事情,UIButton @selector 检测到右按钮,做错了 'else_if' ?

标签 iphone objective-c uibutton selector

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

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++;
     }

@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];
    }
}

现在,它正在将正确的按钮标记打印到 NSLog,如方法中所示,但是每个单个按钮都显示一个以“Franklin Court”为标题的导航栏,每个单独一个,即使当我单击按钮 0 时也是如此,它在控制台中显示“Button 0 clicked”,但仍然执行 else if (whichButton = 1) 代码。

我是不是漏掉了什么?

最佳答案

您在条件中使用 = 运算符而不是 == 运算符,这会进行赋值而不是比较。

由于赋值的返回值是分配的值,首先 whichButton 变为 0 并且计算结果为 false,然后 whichButton 变为 1 并且计算结果为真,无论您做什么,您最终都会选择 Franklin Court。

关于iphone - 有史以来最奇怪的事情,UIButton @selector 检测到右按钮,做错了 'else_if' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429810/

相关文章:

iphone - iOS 是否支持蓝牙 SPP?

objective-c - UITableView 最后两个单元格中的信息与前两个单元格重复

objective-c - 初始化程序元素不是编译时常量错误

ios - 将Title设置为按钮并在单击两次时再次返回第一个标题

iphone - 如何让 UIButton 在触摸时改变颜色

iphone - 为不同公司开发 iPhone 应用程序的最佳实践

iphone - 如何将用户生成的数据迁移到计算机?

iphone - AudioPlaybackComplete使用未声明的标识符自调用方法

iphone - Facebook SDK 3.1 上的 iOS 6 native 支持问题

ios - 如何通过 UIButton 变量调用操作