2013-07-10 5 views
0

Я создал UIButton; на самом деле, несколько кнопок, и я их инициализировал и установил их вПочему моя кнопка не работает?

-(void)viewDidLoad 

способ. Моя проблема теперь связана с методом, который я создал. Я создал typedef enum, чтобы заменить числа для тегов моих кнопок именами в определенных ситуациях. Я не знаю, является ли это проблемой или что, но я смущен тем, почему, когда я нажимаю кнопку (кнопки), они не работают. Мой код ниже.

Моего перечисление:

typedef enum { 
DiseasesStrepThroat = 1, 
DiseasesFlu   = 2, 
DiseasesChickenPox = 3, 
DiseasesSmallPox = 4, 
DiseasesMeasels  = 5, 
DiseasesCommonCold = 6 
} DiseasesTagNumber; 

Я инициализируюсь все объекты UIButton; а также мой IBAction в моем файле .h, поэтому мне не нужно беспокоиться об этой части.

Вот мой взгляд сделал нагрузки

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
[super viewDidLoad];  
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 700, 768, 125)]; 
scrollView.contentSize = CGSizeMake(1000, 125); 
scrollView.backgroundColor = [UIColor darkGrayColor]; 
scrollView.showsHorizontalScrollIndicator = YES; 
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; 
scrollView.autoresizesSubviews = NO; 
[self.view addSubview:scrollView]; 

////////////////////////////////////////// 
//          // 
//  creating all the buttons  // 
//          // 
////////////////////////////////////////// 

// strep throat 
strep = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
strep.frame = CGRectMake(10, 10, 110, 100); 
[strep setTitle:@"Strep" forState:UIControlStateNormal]; 
[strep setTag:DiseasesStrepThroat]; 
[scrollView addSubview:strep]; 

// the flu 
flu = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
flu.frame = CGRectMake(130, 10, 110, 100); 
[flu setTitle:@"Flu" forState:UIControlStateNormal]; 
[flu setTag:DiseasesFlu]; 
[scrollView addSubview:flu]; 

// chicken pox 
chickenPox = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
chickenPox.frame = CGRectMake(250, 10, 110, 100); 
[chickenPox setTitle:@"Chicken Pox" forState:UIControlStateNormal]; 
[chickenPox setTag:DiseasesChickenPox]; 
[scrollView addSubview:chickenPox]; 

// small pox 
smallPox = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
smallPox.frame = CGRectMake(370, 10, 110, 100); 
[smallPox setTitle:@"Small Pox" forState:UIControlStateNormal]; 
[smallPox setTag:DiseasesSmallPox]; 
[scrollView addSubview:smallPox]; 

// measels 
measels = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
measels.frame = CGRectMake(490, 10, 110, 100); 
[measels setTitle:@"Measels" forState:UIControlStateNormal]; 
[measels setTag:DiseasesMeasels]; 
[scrollView addSubview:measels]; 

// common cold 
commonCold = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
commonCold.frame = CGRectMake(610, 10, 110, 100); 
[commonCold setTitle:@"Common Cold" forState:UIControlStateNormal]; 
[commonCold setTag:DiseasesCommonCold]; 
[scrollView addSubview:commonCold]; 

NSArray *array = [[NSArray alloc] initWithObjects:strep, flu, chickenPox, smallPox, measels, commonCold, nil]; 
for(UIButton *b in array) { 
    b.showsTouchWhenHighlighted = YES; 
} 


//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&// 
//          // 
//  CREATING ALL THE TARGETS  // 
//          // 
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&// 

[strep  addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 
[flu  addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 
[chickenPox addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 
[smallPox addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 
[measels addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 
[commonCold addTarget:self action:@selector(showDiseasesWithTag:) forControlEvents:UIControlEventTouchUpInside]; 

} 

и теперь мой метод IBAction

- (IBAction) showDiseasesWithTag:(NSInteger)senderTag { 

switch (senderTag) { 
    case DiseasesStrepThroat: 

     a = [[UIAlertView alloc] 
          initWithTitle:@"H" 
          message:@"yo" 
          delegate:self 
          cancelButtonTitle:nil 
          otherButtonTitles:nil]; 
     [a show]; 
     break; 

    case DiseasesFlu: 
     [UIView animateWithDuration:1.0 animations:^ { 

     }completion:^(BOOL finished) { 

     }]; 
     break; 

    case DiseasesChickenPox: 
     [UIView animateWithDuration:1.0 animations:^ { 

     }completion:^(BOOL finished) { 

     }]; 
     break; 

    case DiseasesSmallPox: 
     [UIView animateWithDuration:1.0 animations:^ { 

     }completion:^(BOOL finished) { 

     }]; 
     break; 

    case DiseasesMeasels: 
     [UIView animateWithDuration:1.0 animations:^ { 

     }completion:^(BOOL finished) { 

     }]; 
     break; 

    case DiseasesCommonCold: 
     [UIView animateWithDuration:1.0 animations:^ { 

     }completion:^(BOOL finished) { 

     }]; 
     break; 

} 
} 

Чтобы очистить что-нибудь вверх, все UIView анимации и завершающие блоки не завершены. В основном я сосредоточен на первом случае. Это потому, что у меня первый случай как 1? Когда я установил значение 0, он все равно ничего не сделал.

Фактическая проблема со всем, когда я нажимаю первую UIButton в своем UIScrollView, я могу нажать ее, но что происходит, кнопка не делает ничего относительно метода IBAction. Кажется, он вообще не звонит.

Любая помощь приветствуется.

+0

Как вы уверены, что метод действия делает не огонь? Вы установили точку останова в 'lldb' или установили вызов' NSLog() '? – trojanfoe

+0

Я только что разместил NSLog() в позиции 1-го случая, и он не вызывает функцию, потому что я не вижу вывода консоли. – user2277872

+0

Вы имеете в виду, что вы разместили его над оператором 'switch()', не так ли? – trojanfoe

ответ

1

ОК, вы просто используете неправильный аргумент метода действия. Оно должно быть:

- (IBAction) showDiseasesWithTag:(id)sender { 
    NSInteger senderTag = [sender tag]; 

    switch (senderTag) { 
     ... 
    } 
} 

Под прошивкой целевой метод может иметь один из трех различных подписей:

- (IBAction)actionMethod; 
- (IBAction)actionMethod:(id)sender; 
- (IBAction)actionMethod:(id)sender forEvent:(UIEvent *)event; 

но никогда:

- (IBAction)actionMethod:(NSInteger)senderTag; 
+0

Ничего себе! Спасибо! Я на самом деле не пытался использовать много разных аргументов, так что это новый опыт обучения, но спасибо за то, что помогли мне решить эту, казалось бы, простую ошибку! – user2277872

+0

@ user2277872 Не беспокойтесь. Счастливое кодирование. – trojanfoe

Смежные вопросы