2013-05-09 70 views
0

我在操作UIButton時遇到了一些問題。我以編程方式創建4個按鈕,但我無法觸發TouchUpInside事件。無法以編程方式設置UIButton操作

我已經閱讀過,但我仍然有麻煩,所以任何指針將不勝感激!

這裏就是我創建並設置按鈕的代碼,它的作用:

UIButton *btn; 

float newWidth = 10; 

for (int i = 0; i < _btnImages.count; ++i) { 
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    CGRect imageFrame = CGRectMake(/*X*/newWidth, /*Y*/height - 80, 65, 65); 
    btn.frame = imageFrame; 
    btn.tag = i; 

    [btn setBackgroundImage:[UIImage imageNamed:[_btnImages objectAtIndex:i]] forState:UIControlStateNormal]; 
    [btn addTarget:self 
      action:@selector(btnSelected:) 
      forControlEvents:UIControlEventTouchUpInside]; 
    [btn setEnabled:true]; 

    [self addSubview:btn]; 
    newWidth = newWidth + 75; 
} 

這裏是btnSelected方法:

-(void)btnSelected:(UIButton *)button 
{ 
    NSLog(@"Button %ld Clicked",(long int)[button tag]); 
} 
+0

您可以驗證添加的幀是否在視圖內。有可能他們不是。 – Anupdas 2013-05-09 15:10:24

+0

for循環在哪裏關閉? 您並未對x和y位置進行更改,因此這些按鈕被添加到另一個之上。 你能澄清一下嗎? – Mohith 2013-05-09 15:18:11

+0

對不起Mohith,我想我在這裏添加了一切,但錯過了我在x軸上移動並關閉for循環的地方! – donpisci 2013-05-09 15:22:28

回答

7

你所示的代碼是好的。 可能的問題是:

  1. 要添加的按鈕到具有禁用用戶交互(或任何其祖先的已用戶交互禁用)的圖。

  2. 您的按鈕被他們的超級視圖剪輯。確保你的按鈕在他們的超級視圖的界限內(並且超級視圖在超級視圖的界限內等)。

  3. 當您的視圖中有手勢識別器時,可能會發生其他問題 - 他們可以在子視圖中延遲&取消觸摸,包括按鈕。確保某些手勢識別器不處理觸摸事件。

+0

認爲這是超級視圖的問題,因爲我在viewController.m中創建了按鈕,現在他們可以工作了,感謝您的幫助! – donpisci 2013-05-09 15:23:17