以编程方式添加带有按钮的视图

JOG*_*JOG 3 uibutton ios

我想以编程方式添加视图和按钮,如下所示.

问题是按钮在点击时没有反应.我的意思是它既不会突出显示也不会调用选择器.

原因是我想为录音(声音文件)实现列表行.列表行应该可以选择向下钻取并有一个播放按钮.所以我得到了一个RecordingView子类UIView,它本身使用构造函数中的目标添加按钮.见下面的代码.

listrow

如果有人有更好的方法来做到这一点,这也可能是一个解决方案.

@implementation MyViewController

- (IBAction) myAction { 
    RecordingView *recordingView = [[RecordingView alloc] initWithFrame:CGRectMake(30, 400, 130, 50)withTarget:self];
    [recordingView setUserInteractionEnabled:YES];
    [[self view] addSubview:recordingView];
}
Run Code Online (Sandbox Code Playgroud)

@implementation RecordingView

- (id)initWithFrame:(CGRect)frame withTarget:(id) target
{
    self = [super initWithFrame:frame];

    UIButton *playButton = [[UIButton alloc] initWithFrame:CGRectMake(185, 5, 80, 40)];
    [playButton setTitle:@"Play" forState:UIControlStateNormal];
    [playButton setTitleColor:[UIColor darkTextColor]forState:UIControlStateNormal];
    // creating images here ...
    [playButton setBackgroundImage:imGray forState: UIControlStateNormal];
    [playButton setBackgroundImage:imRed forState: UIControlStateHighlighted];
    [playButton setEnabled:YES];
    [playButton setUserInteractionEnabled:YES];
    [playButton addTarget: target 
                   action: @selector(buttonClicked:) 
         forControlEvents: UIControlEventTouchDown];

    [self addSubview:playButton];

    return self;
}
Run Code Online (Sandbox Code Playgroud)

当我以相同的方式添加按钮时,直接在视图控制器.m文件中,按钮会在单击时做出反应.所以有一些关于RecordingView.我需要做些什么呢?

另外,有没有更好的方法来为触摸事件提供目标和选择器?

rob*_*off 5

您可能只需要设置userInteractionEnabledYES您的RecordingView.

另一个问题是您创建的RecordingView帧宽为130,但是您将X轴原点设置playButton为185.这意味着playButton它完全超出其超视图的范围.clipsToBoundsis 的默认值NO,因此无论如何都会绘制按钮.但触摸事件永远不会到达按钮,因为当系统命中测试时它们会被拒绝RecordingView.

这来自UIView类参考中hitTest:withEvent:文档:

位于接收者界限之外的点永远不会被报告为命中,即使它们实际上位于接收者的子视图中.如果当前视图的clipsToBounds属性设置为NO并且受影响的子视图超出视图的边界,则会发生这种情况.

你需要使RecordingView框架更宽,或者移动playButton到超级视图的范围内.