0

在我的应用程序中有一个表格视图。When a row in the table view is selected a UIViewappears and shows information. 行标题来自一个 plist 文件,其中包含字符串。plist 文件还包括带有与行标题关联的电话号码的字符串。在自定义 UIView 中,我有一个按钮,当您单击该按钮时,我希望它调用 plist 文件中声明的数字。与用户单击的行关联的数字。

我怎么能做到这一点?

该动作是一个普通的 IBAction:

- (IBAction)callNumber:(id)sender;

它连接到 IB 中的按钮(在 Xcode 4 中)。

如果有人能解决我的问题,我将不胜感激,谢谢。

编辑

为了清楚起见,我想获取与您在表格视图中选择的行相关联的电话号码。plist 中的字符串有一个键,用于电话号码名称:“电话”。

NSString *phone = [[tableList objectAtIndex:indexPath.row] objectForKey:@"phone"];

“tablelist”是一个 NSMutableArray。我想获取密钥“电话”并将其存储在 NSString *电话中。所有这些都在 IBAction 中。发布整个班级会有所帮助吗?

4

4 回答 4

3

对此有一个优雅的解决方案,它是在您设置UITableViewCell. 将 UIButton 的标签设置为行的索引:

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString* CellIdentifier = @"Cell";

    YourCustomCell* cell = (YourCustomCell*)[tableView 
                              dequeueReusableCellWithIdentifier:CellIdentifier];

    //  All the code for loading a cell

    //  Other code you have for configuring the cell

    //  HERE'S THE IMPORTANT PART: SETTING THE
    //  BUTTON'S TAG TO THE INDEX OF THE ROW
    cell.phoneButton.tag = indexPath.row;

    return cell;    
}

然后,在操作代码中,您可以将索引拉出标签:

- (IBAction)callNumber:(id)sender {
    UIButton* button = sender;
    int index = button.tag;
    NSString *phone = [[tableList objectAtIndex:indexPath.row] objectForKey:@"phone"];
    //  Make the phone call
}
于 2011-11-23T21:53:59.943 回答
1

您需要在“自定义视图”上有一个属性,该属性指示所选行的索引路径。您可以将其放在自定义视图控制器的标头中以声明此属性:

@interface MyCustomViewController : UIViewController {
    ...
    NSIndexPath * indexPath;
}
@property (nonatomic, retain) NSIndexPath * indexPath;

然后,像这样设置实现:

@implementation MyCustomViewController
@synthesize indexPath;
...
// only needed if not using ARC
- (void)dealloc {
    self.indexPath = nil;
    ...
    [super dealloc];
}
@end

现在,在该tableView:didSelectRowAtIndexPath:方法中,像往常一样简单地创建视图控制器,但indexPath在其上设置属性以便将来可以访问它:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomViewController * vc = [[MyCustomViewController alloc] initWithBundle:nil nibName:nil];
    [vc setIndexPath:indexPath];
    [self presentModalViewController:vc];
    // if not using ARC
    [vc release];
}

然后,在 中的任何位置MyCustomViewController.m,只需写入self.indexPath.row即可获取所选索引路径的行。

于 2011-11-23T21:53:05.123 回答
0

作为一种快速的临时解决方法,您可以执行以下操作:

单元格选择方法: - 为选择 indexPath.row 保存一个 NSUserDefault

在您的下一个视图中: - 读取读取的任何行的 NSUserDefault 值

然后,这将使下一个视图知道选择了哪个视图,并允许您为其获取正确的数据。

于 2011-11-23T21:48:52.120 回答
0

如果您在 UITableViewCell 中有控件执行需要知道索引路径的操作,则可以使用以下几种方法:

  1. 如果您有一个部分(或带有控件的单元格的已知部分)并且没有将该tag属性用于其他用途,请将行 + 1 存储在tag属性中。然后,当调用该操作时,检索sender.tag - 1并获得行索引。

  2. 从您的控件中向上走超级视图链,直到到达UITableViewCell. [tableView indexPathForCell:cell获取 indexPath的调用。

  3. 创建控件的子类并将 indexPath 存储在控件中。

于 2011-11-23T21:50:58.043 回答