在cellForRowAtIndexPath中未正确设置UIButton标记

Fle*_*lea 2 iphone objective-c ios

在我的手机中,UITableViewCell我有一个UIButton代表手机,当用户触摸时,可以调用表格单元格中特定对象指定的电话号码. 在此输入图像描述

由于我将有多个按钮,并且每个按钮都有一个特定的电话号码,我试图将tag属性设置UIButton为当前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
}
Run Code Online (Sandbox Code Playgroud)

以下是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];
    }
}
Run Code Online (Sandbox Code Playgroud)

GoZ*_*ner 7

标签真的不是处理这个问题的正确方法.你最好使用MyPerson属性为UITableViewCell创建子类. [注意:如果合适的话,将人替换为学校]像这样:

@interface MyPerson : NSObject
@property (...) NSString *phoneNumber;
@property (...) NSString *emailAddress;
@end

@interface MyPersonCell : UITableViewCell
@property (readwrite) MyPerson *person;
- (IBAction) callPhoneNumber;
- (IBAction) sendEmail;
@end
Run Code Online (Sandbox Code Playgroud)

然后在您的tableView:cellForRowAtIndexPath:实现中将单元配置为

cell.person = [get person from datasource for section+row];
Run Code Online (Sandbox Code Playgroud)

此外,UIButton操作链接到单元本身(如上面的代码所暗示)或表视图控制器本身.

如果您使用Xcode故事板,您将需要使用"原型单元",配置MyPersonCell,添加UIButton并将按钮操作链接到单元格.