2012-02-24 94 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

相關問題