ios - 带有 UIButton : which button has been clicked? 的自定义 UITableViewCell

标签 ios uitableview uibutton

我正在使用最新的 SDK 和 XCode 4.2 开发 iOS 4 应用程序。

我有一个包含部分和自定义 UITableViewCellUITableView。每个单元格都有一个 UIButton,所有这些按钮都有相同的 UIControlEventTouchUpInside 目标。

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"CalendarCell";

    CalendarEventCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        NSArray* topLevelObjects =  [[NSBundle mainBundle] loadNibNamed:@"CalendarEventCell" owner:nil options:nil];

        for(id currentObject in topLevelObjects)
        {
            if ([currentObject isKindOfClass:[CalendarEventCell class]])
            {
                cell = (CalendarEventCell *)currentObject;
                [cell.addToCalendarButton addTarget:self action:@selector(addEventToiCal) forControlEvents:UIControlEventTouchUpInside];
                break;
            }
        }
    }
...
}

当用户触摸该按钮内部时,我如何知道被点击的单元格是在哪个部分和行?

最佳答案

在按钮上放置一个标签。例如:

CalendarEventCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil)
{
    NSArray* topLevelObjects =  [[NSBundle mainBundle] loadNibNamed:@"CalendarEventCell" owner:nil options:nil];

    for(id currentObject in topLevelObjects)
    {
        if ([currentObject isKindOfClass:[CalendarEventCell class]])
        {
            cell = (CalendarEventCell *)currentObject;
            [cell.addToCalendarButton addTarget:self action:@selector(addEventToiCal) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
    }
}
cell.addToCalendarButton.tag = ((indexPath.section & 0xFFFF) << 16) |
                               (indexPath.row & 0xFFFF);

您需要将选择器更改为 @selector(addEventToiCal:)并将方法更新为 -(void) addEventToiCal:(UIButton *)sender .

然后您可以将类似以下内容添加到 -addEventToiCal:

if (!([sender isKindOfClass:[UIButton class]]))
    return;
NSUInteger section = ((sender.tag >> 16) & 0xFFFF);
NSUInteger row     = (sender.tag & 0xFFFF);
NSLog(@"Button in section %i on row %i was pressed.", section, row);

关于ios - 带有 UIButton : which button has been clicked? 的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9579605/

相关文章:

ios - 单击多个 UIButton 如何同时播放多个声音?

ios - 以编程方式将 UIButton 添加到 UITableView 但按钮不显示

iphone - Xcode 4 + iOS 4.3 : "No Packager exists for the type of archive"

ios - 使用 Swift 在 iOS 中平滑搜索栏动画

ios - Datepicker maximumDate 在当天早​​些时候停留在昨天

ios - iOS 后台运行任务

ios - 在 UITableView 中实现边距的更好方法?

ios - 如何从表格中删除单元格

objective-c - 对从 coreData 检索到的值求和并在部分中显示

iOS - 解析登录 - 更改按钮标题