button.tag属性在UItableView单元格中不起作用

时间:2011-06-06 06:45:55

标签: iphone uitableview

我在单元的附件视图中添加了下载按钮..我的代码是

button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:@"download.png"];
[button setImage:image forState:UIControlStateNormal];
 //[button setTitle:@"Download" forState:UIControlStateNormal];
[button setFrame: CGRectMake( 110.0f, 3.0f, 80.0f, 30.0f)];
[button addTarget:self action:@selector(someAction) forControlEvents:UIControlEventTouchUpInside];
button.tag = indexPath.row;
cell.accessoryView = button;

我想从单元格的索引路径传递文件名但这不起作用它只需要第一行......

- (void)someAction {

    [self.activityIndicator startAnimating];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [NSString stringWithFormat:@"/%@",[metaArray objectAtIndex:button.tag]]; 
    NSLog(@"%@", button.tag);   
    NSString *path = [NSString stringWithFormat:@"%@/Downloaded Data/%@",[paths objectAtIndex:0],file];

//  NSString *loadFileName = [NSString stringWithFormat:@"/%@/%@",Name,file];
    [self.restClient loadFile:file intoPath:path];
    NSLog(@"Downloaded:%@",file);
}

由于button.tag = indexpath.row而崩溃 如果我没有传递button.tag = indexpath.row它只传递第一行 请帮忙

2 个答案:

答案 0 :(得分:2)

tag是一个整数属性。您正尝试在NSLog中将其打印为对象。你必须像这样打印NSLog(@"%d", button.tag);

实际上,您必须为每个单元格分配单独的下载按钮。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:@"download.png"];
[button setImage:image forState:UIControlStateNormal];
//[button setTitle:@"Download" forState:UIControlStateNormal];
[button setFrame: CGRectMake( 110.0f, 3.0f, 80.0f, 30.0f)];
[button addTarget:self action:@selector(someAction:) forControlEvents:UIControlEventTouchUpInside];
button.tag = indexPath.row;
cell.accessoryView = button;

并定义您的someAction方法,

- (void)someAction:(id)sender {

    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", button.tag); 
    [self.activityIndicator startAnimating];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [NSString stringWithFormat:@"/%@",[metaArray objectAtIndex:button.tag]];   
    NSString *path = [NSString stringWithFormat:@"%@/Downloaded Data/%@",[paths objectAtIndex:0], file];
   //NSString *loadFileName = [NSString stringWithFormat:@"/%@/%@",Name,file];
    [self.restClient loadFile:file intoPath:path];
    NSLog(@"Downloaded:%@", file);
}

答案 1 :(得分:1)

UITableView的行是可重用的,不要用行索引设置标签而不是我们这个方法

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    id rowObject = [myArray objectAtIndex:indexPath.row];
}