在我的UITableViewCell
我有一个UIButton
代表一个电话,当用户触摸它时,假设它会拨打由表格单元格中的特定对象指定的电话号码。
由于我将有多个按钮,并且每个按钮都有一个特定的电话号码,我试图将tag
属性设置UIButton
为 current indexPath.row
,但是它适用于前 6 个单元格,但是当单元格开始被重用时,标签就会回到 0所有按钮。我将按钮的标签设置在重用块之外,我认为这应该是这样做的正确方法,以便识别每个唯一的单元格。
为了测试,我还将cell.tag
属性设置为indexPath.row
并且它工作得很好,所以它肯定是与 UIButton 隔离的。关于我可能做错了什么的任何想法?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SchoolCellIdentifer = @"SchoolCellIdentifier";
SchoolInfoItem *item = [self.schoolArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SchoolCellIdentifer];
// If the cell doesn't existing go ahead and make it fresh.
if (cell == nil)
{
// Begin Phone button view
UIButton *phoneButton = [[UIButton alloc] initWithFrame:CGRectMake(67, 70, 35, 35)];
phoneButton.tag = 80;
UIImageView *phoneView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"phone-icon.png"]];
phoneView.frame = CGRectMake(2.5, 2.5, 30, 30);
[phoneButton addSubview:phoneView];
[cell.contentView addSubview:phoneButton];
}
cell.tag = indexPath.row;
phoneButton = (UIButton *) [cell viewWithTag:80];
[phoneButton addTarget:self action:@selector(callPhoneNumber:) forControlEvents:UIControlEventTouchUpInside];
phoneButton.tag = cell.tag;
NSLog(@"phoneButton tag: %d", phoneButton.tag);
NSLog(@"cell tag:%d", cell.tag);
return cell
}
这是 TouchEvent 的方法:
- (void) callPhoneNumber:(id)sender
{
UIButton *button = (UIButton *) sender;
SchoolInfoItem *schoolItem = [self.schoolArray objectAtIndex:button.tag];
NSLog(@"tag at: %d", button.tag);
if ([schoolItem.MainPhone length] != 0)
{
NSString *URLString = [@"tel://" stringByAppendingString:schoolItem.MainPhone];
NSURL *URL = [NSURL URLWithString:URLString];
NSLog(@"%@", URL);
[[UIApplication sharedApplication] openURL:URL];
}
}