0
我明白如何獲得按鈕點擊,如果我在UITableView行中有一個按鈕,但我無法弄清楚的是向UITableViewCell子類添加按鈕並獲得點擊它在我的UITableView類中。我想我犯的錯誤是將所有內容都放入layoutSubviews方法中。有人可以指點我正確的方向嗎?子類化UITableViewCell並在子類中處理UIButton
-(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];
}
聽起來不錯,謝謝。這將是我所指的UITableViewController類,而不是UITableView抱歉..我想..現在沒有我的Mac與我在一起。所以關於添加按鈕和初始化,我只需要添加一個我自己的方法來進行初始化並在我的自定義單元格對象上調用它。涼。那麼每次標籤的文本屬性被改變時,layoutSubviews會被調用嗎? (我將更改cellForRowAtIndexPath中的標籤內容。) – SparkyNZ
UITableViewCell的指定初始化程序是initWithStyle:reuseIdentifier:因此您可以實現此方法並在其中添加子視圖。單元格的layoutSubviews方法不會通過設置單元格中標籤的text屬性來觸發,但每次單元格框架更改時都會調用它。看到這個問題的更多信息:http://stackoverflow.com/questions/728372/when-is-layoutsubviews-called –
我無法獲得點擊呼叫我的UITableViewController方法:PeriodCell * cellPeriod =(PeriodCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cellPeriod == nil) cellPeriod = [[[PeriodCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // PDS:初始化單元格上的我的按鈕等 [cellPeriod initPeriodCell]; [cellPeriod.myButton1 addTarget:self action:@selector(buttonClickedStopWatch :) forControlEvents:UIControlEventTouchUpInside]; } – SparkyNZ