这使我烦恼!我只是想以编程方式向导航栏中添加右侧的“闪光灯”按钮,无论出于何种原因,我都无法使其显示。我的代码如下。谁能帮我?提前致谢。

 //Note: flashButton is declared as a UIButton property in .h, and synthesized in .m
    UIView *flashContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];

    [flashButton addTarget:self action:@selector(toggleTorch) forControlEvents:UIControlEventTouchUpInside];
    [flashButton setBackgroundImage: [UIImage imageNamed:@"FlashIconInactive_small.png"] forState:UIControlStateNormal];
    [flashButton setBackgroundImage: [UIImage imageNamed:@"FlashIconActive_small.png"] forState:UIControlStateHighlighted];

    [flashContainer addSubview:flashButton];
    [flashButton sizeToFit];

    UIBarButtonItem *flashButtonItem = [[UIBarButtonItem alloc] initWithCustomView:flashContainer];

    scannerVC.delegate = self;
    scannerVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelTapped)];
    [[scannerVC navigationItem] setRightBarButtonItem:flashButtonItem];

最佳答案

flashButton是否通过IBOutlet连接到xib或情节提要中的按钮?如果不是,则需要使用+[UIButton buttonWithType:]创建UIButton的实例。

尝试进行的另一项测试是在第一行上设置一个断点(addTarget:一个),然后在调试器中输入po flashButton。输出是什么?如果为零,则您的按钮不存在,需要创建。

10-04 22:30