我认为你可以使用 UIView 的 tag 属性。
我的程序可能如下所示。
- (NSInteger)encodeTagForButtonID:(NSString *)buttonID;
- (NSString *)decodeButtonIDFromEncodedTag:(NSInteger)tag;
当我创建一个 UIButton 时,我将按钮的 ID 编码为 tag。 buttonID 可能是有意义的,或者它只是一个整数,就像定义的值一样。 action的签名可以是这样的形式:-(void)buttonAction:(id)sender;,我可以从sender中获取tag的值>.
编辑:
例如,在 UITableView 的数据源方法中。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
/// new an autoreleased cell object
}
// Configure cell
cell.tag = [self encodeTagWithIndexPath:indexPath];
return cell;
}
当我触摸这个单元格时,我从标签中检索 indexPath。
UIButton 是 UIView 的子类,所以它也有 tag。例如,我制作了一个自定义 actionSheet,它包含一个 UIButtons 列表。当我按下 UIButton 时,我需要知道我按下了哪个按钮。所以,我将行信息分配给标签。
NSArray *buttonListInActionSheet = ....; ///< UIButton array, a button per row.
for (int idxBtn = 0; idxBtn < [buttonListInActionSheet count]; ++idxBtn) {
UIButton *btn = [buttonListInActionSheet objectAtIndex:idxBtn];
btn.tag = (100 + idxBtn);
}
当我点击按钮时,我可以通过
获取行信息
- (void)buttonTouched:(id)sender {
UIButton *btn = (UIButton *)sender;
NSInteger idxBtn = (btn.tag - 100);
}