【问题标题】:How to get UIView Controller of custom cell contained in如何获取自定义单元格的 UIView 控制器包含在
【发布时间】:2013-07-08 11:49:13
【问题描述】:

我有一个视图控制器 在那个自定义单元格中有一个表格视图。

我在自定义单元格中有一个按钮

MyViewController
---View
------TableView
-------------Custom cell
-------------------UIButton

我想在自定义单元格类中为该按钮实现按钮操作。

我想通过单击按钮来呈现另一个名为 mailPage 的视图控制器

-(IBAction)webButtonClicked:(id)sender
{
  [self presentModalViewController:mailpage animated:YES];
}

但是这里 self 表示 CustomCell, 即使我 尝试使用 superview 我也没有让我的视图控制器来代替 self

我试过这样但没用。

MyViewController *myViewController =self.superview 

如何获取包含当前自定义单元格的视图控制器

【问题讨论】:

  • 您是如何在表格视图中使用自定义单元格的?发布该代码....

标签: ios objective-c uitableview uiviewcontroller custom-cell


【解决方案1】:

我强烈建议您将视图控制器表示逻辑放在视图控制器中,而不是 UITableViewCell

由于您已经在使用自定义单元格,这将相当简单。只需为您的自定义单元定义一个新协议,并让您的视图控制器充当代理。或者,根据this answer here,您可以完全放弃委托,而只需让您的视图控制器充当按钮的目标。

您的自定义 UITableViewCell 真的不应该对它所显示的视图控制器有任何依赖关系或知识。

【讨论】:

    【解决方案2】:

    简单的方法是为单元格中的按钮设置一个唯一标签,在 cellForRowAtIndexpath 方法中,您可以获得按钮实例

    UIButton *sampleButton=(UIButton *)[cell viewWithTag:3]; 
    

    并将动作设置为

        [sampleButton addTarget:self action:@selector(sampleButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    

    并在视图控制器中设置动作

    -(void)sampleButtonPressed:(id)sender
    {
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
          static NSString *CellIdentifier = @"OpenHouseListCustomCell";
          OpenHouseListCustomCell *cell = (OpenHouseListCustomCell *)[tblOpenHouses dequeueReusableCellWithIdentifier:CellIdentifier];
          if(cell == nil) {
              NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"OpenHouseListCustomCell" owner:self options:nil];
              cell = [nib objectAtIndex:0];
              cell.showsReorderControl = NO;
              cell.selectionStyle = UITableViewCellSelectionStyleNone;
              cell.backgroundColor=[UIColor clearColor];
              [cell.btn1 addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
          }
      
          cell.btn1.tag = indexpath.row;
          return cell;
      }
      
      -(void) ButtonClicked {
          //your code here...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多