2012-02-24 88 views
3

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

问题是,按钮不响应点击。我的意思是它既不会突出显示或调用选择器。

原因是我想实现记录(声音文件)的列表行。列表行应该是可选的,用于下钻并具有播放按钮。所以我得到了一个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]; 
} 

@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。我需要在这里做什么不同?

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

+0

这是你的实际代码吗?你在哪里声明或填充两个UIImage变量(imGrey和imRed)?你在init方法中,所以他们不能成为ivars?关于你的问题,你说你想要一个录音列表 - 你是在一个表格视图之后?您的录制视图可以是表格单元格子类吗? – jrturton 2012-02-24 08:02:20

+0

的确,我省略了创建图像的代码。这是我的实际代码,但为了简单起见,我在发布时删除了内容。我会澄清这一点。是的,录制视图可以是表格单元格。我是从代码构建iOS UI的新手。这是我的第一个,所以任何方向前进是值得欢迎的。:) – JOG 2012-02-24 08:57:15

+0

@jrturton:是的,我打算在UITableViewDelegate中,在方法' - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath'中使用此代码。 ...当我开始工作时,就是这样。 ^^ – JOG 2012-02-24 17:31:40

回答

5

您可能只需在RecordingView上设置userInteractionEnabledYES即可。

另一个问题是,要创建的RecordingView具有130帧的宽度,但你的playButton X轴原点设定为185.这意味着playButton完全是它的父的边界的外部。 clipsToBounds的默认值为NO,因此无论如何都要绘制该按钮。但触摸事件永远不会到达该按钮,因为当系统碰撞时,它们被拒绝 - 测试RecordingView

这是从hitTest:withEvent:文档中UIView Class Reference

点摆在接收器的边界之外从不报告为命中,即使他们实际上在于接收器的子视图中的一个内。如果当前视图的clipsToBounds属性设置为NO,并且受影响的子视图超出视图的界限,则会发生这种情况。

您需要使RecordingView的框架变宽,或者将playButton移动到其超视图范围内。

+0

不,没有工作。我正在更新问题代码。 – JOG 2012-02-24 13:00:41

+0

我修改了我的答案。 – 2012-02-24 17:32:33

+0

这是宽度,thanx如此之多 – JOG 2012-02-24 17:38:44

相关问题