我想以编程方式添加视图和按钮,如下所示。以编程方式使用按钮添加视图
问题是,按钮不响应点击。我的意思是它既不会突出显示或调用选择器。
原因是我想实现记录(声音文件)的列表行。列表行应该是可选的,用于下钻并具有播放按钮。所以我得到了一个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 2012-02-24 08:02:20
的确,我省略了创建图像的代码。这是我的实际代码,但为了简单起见,我在发布时删除了内容。我会澄清这一点。是的,录制视图可以是表格单元格。我是从代码构建iOS UI的新手。这是我的第一个,所以任何方向前进是值得欢迎的。:) – JOG 2012-02-24 08:57:15
@jrturton:是的,我打算在UITableViewDelegate中,在方法' - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath'中使用此代码。 ...当我开始工作时,就是这样。 ^^ – JOG 2012-02-24 17:31:40