0

我正在使用帶有TableViewCell的TableView。我以編程方式向單元添加了ImageView,Text和uibutton。按鈕的框架對於縱向和橫向方向設置不同。但是當設備從縱向旋轉到橫向時,顯示的是兩個按鈕而不是一個。設備旋轉時在TableView Cell中顯示的兩個uibutton

我試圖刪除按鈕時,在橫向模式按鈕不工作。

switch ([indexPath section]) 
{ 

    case 0: 
    { 
     cell.imageView.image = [UIImage imageNamed:@"active.png"]; 
     cell.textLabel.text = @"Application Name"; 
     self.uninstallApplicationButton = [[UIButton alloc] init]; 
     self.uninstallApplicationButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [self.uninstallApplicationButton setTitle:@"Install" forState: UIControlStateNormal]; 
     [self.uninstallApplicationButton setBackgroundColor:[UIColor brownColor]]; 

     UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 

     if (device == UIUserInterfaceIdiomPhone) 
     { 
      if (UIInterfaceOrientationIsLandscape(orientation)) 
      { 
       self.uninstallApplicationButton.frame = CGRectMake(490.0, 25.0, 65.0, 30.0); 
      } 
      else if(UIInterfaceOrientationIsPortrait(orientation)) 
      { 
       self.uninstallApplicationButton.frame = CGRectMake(250.0, 25.0, 65.0, 30.0); 

      } 
     } 

     else if(device == UIUserInterfaceIdiomPad) 
     { 
      self.uninstallApplicationButton.frame = CGRectMake(600.0, 25.0, 150.0, 30.0); 
     } 

    } 
    [cell.contentView addSubview:uninstallApplicationButton]; 
     break; 
+1

請包括相關的代碼。 – Caleb

+0

@Caleb我添加了代碼。 – Amon

+1

你在哪裏寫這段代碼?它可能會運行多次。 – Desdenova

回答

0

您需要在alloc init之前從其超級視圖中刪除按鈕。

+0

它不工作。它會刪除按鈕,但不會再將其添加到視圖中。 – Amon

+0

從你的代碼中刪除這行:self.uninstallApplicationButton = [[UIButton alloc] init]; – KKRocks

+0

也將此鏈接引用到在tableview單元格中添加按鈕的過程:http://stackoverflow.com/questions/7721364/add-buttons-programatically-to-table-view-cells?answertab=votes#tab-top – KKRocks

1

你說的代碼是在你的-cellForRow(at:)方法。由於表格視圖重用了它們的單元格,因此您的代碼必須考慮它所配置的單元格可能以前已經配置過。一個好的方法是避免在這個方法中爲你的單元格添加任何按鈕或其他視圖,只需將它們添加到故事板中即可。如果您必須將視圖添加到單元格中,則應刪除以前添加的視圖或僅重新使用它們,避免再次添加它們。