UIButton 作为子视图没有响应

UIButton as a subview not responding

我有一个 UIButton inside a UIView inside a UIImageView that is not responding to touchs。我不知道为什么。我已将代码分解为最简单的形式,同时仍在执行我原来的程序所做的事情。

#import "TestVideoViewController.h"

@interface TestVideoViewController ()

@property (strong, nonatomic)UIImageView *panel;
@property (strong, nonatomic)UIView *panelSC;
@property (strong, nonatomic)UIButton *panelButtonSC;
@property (strong, nonatomic)UIButton *videoButton;

@end

@implementation TestVideoViewController

-(void) viewDidLoad {

    _panelButtonSC  = [UIButton buttonWithType:UIButtonTypeCustom];
    [_panelButtonSC addTarget:self action:@selector(buttonPressedSC:) forControlEvents:UIControlEventTouchUpInside];
    [_panelButtonSC setTitle:@"Open" forState:UIControlStateNormal];
    _panelButtonSC.frame = CGRectMake(511, 701, 66, 67);

    _panel = [[UIImageView alloc] initWithFrame:CGRectMake(100, 768, 824, 600)];
    _panel.backgroundColor = [UIColor whiteColor];

    _panelSC = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 784, 560)];
    _panelSC.backgroundColor = [UIColor whiteColor];

    _videoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_videoButton addTarget:self action:@selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
    [_videoButton setTitle:@"Play" forState:UIControlStateNormal];
    [_videoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _videoButton.frame = CGRectMake(400, 400, 200, 40);

    [_panelSC addSubview:_videoButton];

    [_panel addSubview:_panelSC];

    [self.view addSubview:_panel];
    [self.view addSubview:_panelButtonSC];

}

- (IBAction)buttonPressedSC:(UIButton*)sender {

    [self animatePanelUp];
}

- (IBAction)playVideo:(UIButton*)sender {

    NSLog(@"play video");
}

- (void) animatePanelUp {
    [UIView animateWithDuration: 0.5
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         _panel.frame = CGRectMake(47, 166, 929, 602);
                     }
                     completion:nil];

}

@end

我已经查看了这里所有类似的答案。据我所知,我所有的框架都是正确的。我必须缺少一些简单而愚蠢的东西。为什么 "playVideo" 方法永远不会触发?唯一有效的情况是我将按钮直接添加到 self.view.

确保父视图启用了用户交互。 UIImageView 默认有 userInteractionEnabled false。

_panel.userInteractionEnabled = true

当您将几个子视图相互添加时,请检查您的按钮是否可点击,并且没有其他子视图占用触摸事件,并总体确保您的视图启用了用户操作。

提示:

使用的图像视图可能存在一些问题,因为默认情况下它会禁用用户交互。

改用 UIView 或这样做:

_panelSC.userInteractionEnabled = true;

UIImageView 默认将 userInteractionEnabled 设置为 false - 添加以下代码行即可。

_panel.userInteractionEnabled = true;