我正在使用最新的 SDK 和 XCode 4.2 开发 iOS 4 应用程序。
我有一个包含部分和自定义 UITableViewCell
的 UITableView
。每个单元格都有一个 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/