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

3
我想以编程的方式添加一个视图和按钮,如下所示。
问题是该按钮不会响应点击事件。我的意思是它既没有高亮显示也不调用选择器。
原因是我想实现录音选项列表行,并带有播放按钮。该列表行应可选择以进行深入分析。因此,我得到了一个RecordingView,该子类化UIView,它本身使用构造函数中的目标添加按钮。请参见下面的代码。
如果有人有更好的方法来做到这一点,那么也可以是一种解决方案。 @implementation MyViewController
- (IBAction) myAction { 
    RecordingView *recordingView = [[RecordingView alloc] initWithFrame:CGRectMake(30, 400, 130, 50)withTarget:self];
    [recordingView setUserInteractionEnabled:YES];
    [[self view] addSubview:recordingView];
}

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

当我以相同的方式向视图控制器.m文件中直接添加按钮时,按钮会对点击作出反应。 因此,RecordingView存在某些问题。这里我需要做些什么不同的事情吗?

此外,是否有更好的方法来提供触摸事件的目标和选择器?


这是你实际的代码吗?你在哪里声明或填充两个UIImage变量(imGrey和imRed)?你在一个init方法中,所以它们不能是ivars?关于你的问题,你说你想要一个录音列表 - 你是想要一个表视图吗?你的录音视图可以是一个表格单元子类吗? - jrturton
是的,我省略了创建图像的代码。这是我的实际代码,但为了简单起见,我在发布时删除了一些内容。我会澄清这一点。是的,录制视图可以是一个表格单元格。我是从代码构建iOS UI的新手之一。这是我的第一个项目之一,所以任何进一步的指导都是受欢迎的。 :) - JOG
@jrturton:是的,我计划在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中使用这段代码。...不过前提是我得让它正常工作。^^ - JOG
1个回答

5
您可能只需要在RecordingView上将userInteractionEnabled设置为YES

另一个问题是,您创建RecordingView时使用了130的框架宽度,但是您将playButton的X轴原点设置为185。这意味着playButton完全超出了其父视图的边界。 clipsToBounds的默认值为NO,因此按钮仍会被绘制。 但是,当系统进行命中测试时,触摸事件永远不会到达按钮,因为它们被拒绝了。

这是来自UIView Class Reference中的hitTest:withEvent:文档:

即使实际上位于接收器的子视图之一中,也永远不会报告位于接收器边界之外的点作为命中。如果当前视图的clipsToBounds属性设置为NO并且受影响的子视图超出了视图的边界,则可能会发生这种情况。

您需要将RecordingView的框架宽度加宽,或将playButton移到其父视图的边界内。


这是宽度,非常感谢。 - JOG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接