2014-01-21 57 views
0

美好的一天! 這裏有一個問題:我在我的UITableView增加細胞的按鈕編程這樣的:如何在單元子視圖中找到按鈕

UIButton *button = [[UIButton alloc] initWithFrame:buttonFrame]; 

[button setImage:[UIImage imageNamed:@"Button_off_weather"] forState:UIControlStateNormal]; 

button.tag = indexPath.row; 

[button addTarget:self action:@selector(buttonCityTapped:) forControlEvents:UIControlEventTouchUpInside]; 
[cell addSubview: button]; 

它工作正常。 然後我想找到它的表格和關閉這樣的:

NSMutableArray *cells = [[NSMutableArray alloc] init]; 
for (NSInteger j = 0; j < [_tableView numberOfSections]; ++j) 
{ 
    for (NSInteger i = 0; i < [_tableView numberOfRowsInSection:j]; ++i) 
    { 
     [cells addObject:[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]]; 

     for (UITableViewCell *cell in cells) 
     { 
      for (id theView in cell.subviews) { 

       if ([theView isKindOfClass:[UIButton class]]) { 
        [theView performSelector:@selector(buttonOff:)]; 
       } 

      } 

     } 
    } 
} 

這不起作用。有什麼想法嗎?

+0

請清楚地分享你的問題。 – sathiamoorthy

回答

3

使用@property創建自定義單元格子類,使按鈕可用。這是正確的做法。

您目前的方法目前和將來都會出現錯誤。儘量不要依賴遍歷視圖層次結構的代碼,特別是如果您無法控制視圖層次結構的某些部分(如單元格子視圖)。

+0

感謝您的諮詢!我會像你說的那樣去做。 – Pavel

0

選中此項:適用於我。

int sections = [self.tableView numberOfSections]; 
    for (int i=0; i<sections; i++) { 
     //For the Custom cell 
     NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:i] ; 
     CellStar *cell =(CellStar *) [self.tableView cellForRowAtIndexPath:myIP]; 

     UITextView *txtVi ; 

     NSArray *subviews = cell.contentView.subviews; 

     for(id element in subviews) { 
      if ([element isKindOfClass:[UITextView class]]){ 
       NSLog(@"element is a UItextView\n"); 
       txtVi = (UITextView *)element; 

      } 
      if([element isKindOfClass:[UIButton class]]){ 
       UIButton *btn = (UIButton *) element; 

       NSLog(@"element is UIButton\n"); 
      } 
     } 
     //[self.tableView reloadData]; 
    } 
1

使用枚舉與[cell.contentView subviews]

for(UIView *view in [cell.contentView subviews]) 
    { 
     if([view isKindOfClass:[UIButton class]]) 
     { 
         [theView performSelector:@selector(buttonOff:)]; 

     } 
    } 
+0

不起作用( – Pavel

相關問題