0

I understand how to get button clicks if I have a button within a row of UITableView but what I cannot figure out is the correct way to add a button to a UITableViewCell subclass and get the clicks for it within my UITableView class. I think I'm making the mistake of putting everything into the layoutSubviews method. Can somebody please point me in the right direction?

-(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];
}
4

1 回答 1

4

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

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

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

于 2012-07-03T20:34:58.220 回答