[英]How to do action using Button in UITableViewCell?
我有一個在CustomCell中創建的按鈕。
- (IBAction)onoffBtn:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
if (button.selected)
{
// Do action 1
}
else
{
// Do action 2
}
}
當我運行它時,該按鈕顯示在我在TableViewController中創建的UITableView內的單元格中。 我可以將onoffBtn按下我的單元格,但它無法執行操作。 我該如何做才能使我的按鈕起作用?
這是我的TableViewController.m中的cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier]];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = _customCell;
_customCell = nil;
}
// Show my cell
return cell;
}
還有其他問題,我應該在哪里寫流程? 在我的TableViewController.m或CustomCell.m中? 如果您不介意,請向我提供代碼和說明,此處是新內容,並且仍在學習中。 我想了解您編寫的每一行代碼。 謝謝。
更新:
到目前為止,這是我在TableViewController.m中的cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier]];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = _customCell;
_customCell = nil;
}
button.tag = indexPath.row;
cell.titleLabel.text = [titleArray objectAtIndex:indexPath.row];
cell.timerLabel.text = [timeArray objectAtIndex:indexPath.row];
time = [[secondArray objectAtIndex:indexPath.row] integerValue];
NSLog(@"Title %@, time %@, second %@, time %i, tag %d", titleArray, timeArray, secondArray, time, button.tag);
return cell;
}
這是日志說:
2012-08-04 17:38:36.257 Table[1269:f803] Title (
"Test 1",
"Test 2"
), time (
"10 secs",
"5 secs"
), second (
10,
5
), time 10, tag 0 // tag 0 for cell 1
2012-08-04 17:38:36.261 Table[1269:f803] Title (
"Test 1",
"Test 2"
), time (
"10 secs",
"5 secs"
), second (
10,
5
), time 5, tag 0 // tag should be 1 for cell 2 but it said 0. How to fix it?
這是您如何在細胞中添加按鈕的動作
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ADDING A BUTTON WITH TARGET
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundRect];
btn.frame = CGRectMake(0, 0, 50, 50);
btn.showsTouchWhenHighlighted = YES;
btn.tag = indexPath.row;
[btn addTarget:self action:@selector(onoffBtn:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
return cell;
}
- (IBAction)onoffBtn:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
if (button.selected)
{
// Do action 1
}
else
{
// Do action 2
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.