对UITableViewCell进行子类化并在子类中处理UIButton

时间:2012-07-03 20:10:05

标签: uitableview uibutton subclass

如果我在UITableView的一行中有一个按钮,我理解如何获得按钮点击,但我无法弄清楚的是将按钮添加到UITableViewCell子类并在我的UITableView类中获得点击的正确方法。我想我把错误放在layoutSubviews方法中。有人可以指出我正确的方向吗?

-(void) layoutSubviews 
{
//  UIButton *myButton1; <- This is declared as a property in my subclass header file

  [super layoutSubviews];

  //self.textLabel.frame = CGRectMake(0, 0, 40, 20);

  //        cell.textLabel.text = timeElapsed;
  self.textLabel.frame = CGRectMake( 5, 5, 80, self.frame.size.height - 10 );
  self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;   

  // Don't need UIButton alloc because method below does it for us..
  myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

  //CGRect cellFrame = [self.tableView rectForRowAtIndexPath:indexPath];
  CGRect cellFrame = self.frame;

  myButton1.tag = idButton;

  int nButtonWidth  = 80;
  int nButtonHeight = 30;
  int nActualCellWidth = cellFrame.size.width - 40;
  int nButtonDeltaX = ( nActualCellWidth      - nButtonWidth  ) / 2;
  int nButtonDeltaY = ( cellFrame.size.height - nButtonHeight ) / 2;
  myButton1.frame = CGRectMake( nButtonDeltaX, nButtonDeltaY, nButtonWidth, nButtonHeight );      

  [myButton1 setTitle:@"OK" forState:UIControlStateNormal];

  // PDS: Add delaget for stopwatch clicking..
//  [myButton1 addTarget:self action:@selector(buttonClickedStopWatch:) forControlEvents:UIControlEventTouchUpInside];  

  [self.contentView addSubview:myButton1];      
  [self.contentView bringSubviewToFront:myButton1];
}

1 个答案:

答案 0 :(得分:4)

首先,可以多次调用layoutSubviews,这样就不是创建按钮并将其添加到视图层次结构的好地方。这将导致每次都创建一个新按钮。您应该在指定的初始化程序中创建按钮,并仅使用layoutSubviews来设置框架等。

其次,UITableView的实例通常不是处理按钮点击的好地方。这通常是UIViewController的子类的任务。

无论您选择哪个类来处理点按操作,都可以在单元格中为自定义按钮添加属性。然后让UITableView或UIViewController通过访问属性并将target设置为self来为该控件事件添加操作目标。