我想以編程方式添加視圖和按鈕,如下所示。以編程方式使用按鈕添加視圖
問題是,按鈕不響應點擊。我的意思是它既不會突出顯示或調用選擇器。
原因是我想實現記錄(聲音文件)的列表行。列表行應該是可選的,用於下鑽並具有播放按鈕。所以我得到了一個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