2013-10-31 88 views
0

我有一個Xcode 5按鈕問題。Button click not registereding

我在UIViewController上編程式地創建了一些按鈕,然後想要註冊點擊這些按鈕。我使用NSLog來跟蹤點擊次數,但似乎沒有在日誌中註冊點擊次數。

任何人都可以幫忙嗎?

最終目的是在每個按鈕點擊後繼續到下一個UIViewController,但只是測試以查看按鈕點擊是否先註冊。

這裏是我如何創建viewDidLoad(僅顯示1)按鈕。 注意:if-statement僅用於檢查在先前視圖中按下哪些按鈕。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view. 

    NSString *myString = [NSString stringWithFormat:@"%d", self.tagNumber ]; 

    if (self.tagNumber == 1) 
    { 
     hotelButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     hotelButton.tag = 1; 
     hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f); 

     UIImage *buttonImage1 = [UIImage imageNamed:@"buttonImage1.png"]; 
     [hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal]; 
     [self.view addSubview:hotelButton]; 

     // Add targets and actions 
     [hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside]; 
    } 

}

這裏是我如何檢查按鈕點擊

- (void) buttonClicked 
{ 
    NSLog(@"Button %i clicked", hotelButton.tag); 
} 

注:我也試過如下:

- (void) buttonClicked:(UIButton *) button 
{ 
    NSLog(@"Button %ld clicked", (long int)[button tag]); 
} 

但是,這給了一個錯誤「未申報選擇器buttonClicked「在我的viewDidLoad指向action @選擇器):

[hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside]; 

回答

3

使用此:

[hotelButton addTarget:self action:@selector(buttonClicked) 
    forControlEvents:UIControlEventTouchUpInside]; 

從蘋果文檔:

UIControlEventTouchUpInside 
A touch-up event in the control where the finger is inside the bounds of the control. 

UIControlEventTouchUpOutside 
A touch-up event in the control where the finger is outside the bounds of the control 

而且該方法是:

- (void) buttonClicked 
{ 
    NSLog(@"Button %i clicked", hotelButton.tag); 
} 
+0

好斑,完全錯過了。必須打錯輸入。謝謝。 – heyred

1

試試這個,

[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

,並通過發件人,

- (void) buttonClicked:(UIButton*)sender 
{ 
    NSLog(@"Button %i clicked", [sender tag]); 
} 
1

嘗試和改變外到內,

[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
1

已修改了,如果條件。請按照: -

if (self.tagNumber == 1) 
    { 
     hotelButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     hotelButton.tag = 1; 
     hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f); 

     UIImage *buttonImage1 = [UIImage imageNamed:@"buttonImage1.png"]; 
     [hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal]; 
hotelButton.showsTouchWhenHighlighted = YES; 
hotelButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10); 
     [hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside]; 
     [self.view addSubview:hotelButton]; 

    }