Spa*_*yNZ 1 subclass uibutton uitableview
我知道如果我在 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];
}
Run Code Online (Sandbox Code Playgroud)
首先,layoutSubviews 可能会被多次调用,因此这实际上不是创建按钮并将其添加到视图层次结构的好地方。这将导致每次创建一个新按钮。您应该在指定的初始值设定项中创建按钮,并且仅使用layoutSubviews 来设置框架等。
其次,UITableView 的实例通常不是处理按钮单击的好地方。这通常是 UIViewController 子类的任务。
无论您选择哪个类来处理点击操作,首先要在单元格中为自定义按钮添加属性。然后让 UITableView 或 UIViewController 通过访问属性并将目标设置为 self 来添加该控件事件的操作目标。
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |