2013-07-23 20 views
4

我創建了一個按鈕,就像下面的代碼一樣,但它不會在日誌中響應(應該顯示「ha」)。最奇怪的部分是我已經能夠得到這個確切的代碼在集合視圖中工作,但通常不在視圖控制器上。我在做什麼錯按鈕按「myAction」?以編程方式在iOS上創建按鈕,但按下時沒有任何操作

-(void)viewDidLoad { 
    UIButton *buttonz = [UIButton buttonWithType:UIButtonTypeCustom]; 
     buttonz.frame = CGRectMake(160, 0, 160, 30); 
     [buttonz setTitle:@"Charge" forState:UIControlStateNormal]; 
     [buttonz addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; 
     [buttonz setEnabled:YES]; 

     [buttonz setBackgroundColor:[UIColor blueColor]]; 

     //add the button to the view 
     [backImageView addSubview:buttonz]; 
} 

-(void)myAction:(id)sender { 
NSLog(@"ha"); 
    [self resignFirstResponder]; 
    NSLog(@"ha"); 
} 
+0

也不要忘記添加[super viewDidLoad]; in viewDidLoad – Yan

回答

6

1)

你並不需要「resignFirstResponder」上的按鈕(看起來像極了我看時間「resignFirstResponder」是文本字段或文本視圖)。

2)

變化從UIControlEventTouchUpInside控制事件來UIControlEventTouchDown

3)

父的UIImageView可能沒有 「userInteractionEnabled」 設置爲真,這意味着事件將不會被將會傳播(或發送)到子視圖。

爲了使這些事件提供給子視圖,通過更改父視圖的userInteractionEnabled屬性:補充說,子視圖之前

backImageView.userInteractionEnabled = YES; 

+1

這是第三個。謝謝。 – user2495313

1

默認情況下,圖像userInteractionEnabled被禁用。所以,你必須啓用它backImageView.userInteractionEnabled = YES;

相關問題