3

我是 iphone 新手。我有一个小疑问(即),我创建了一个表格视图,其中我将所有书名和下载选项放在每个单元格中的该特定书,如下所示

Genesis    Download
Exodus     Download
Leviticus  Download

这是上面的Genesis,Exodus,Leviticus是书名,下载是下载这本书的按钮,我在表格视图中有66本不同的书。我的问题是当我们点击下载按钮时,我想获得相应的书名表格视图单元格。我的代码如下

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 66;

}



- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UIButton *downloadButton = nil;
//this is the custom cell i have created one class for this in that i am place the string titlelabel.
        CustomCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) 
        {
            cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
             downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
            downloadButton.frame = CGRectMake(220,10,50,30);
            [downloadButton setImage:[UIImage imageNamed:@"download.png"] forState:UIControlStateNormal];
            [downloadButton addTarget:self action:@selector(downloadButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            downloadButton.backgroundColor = [UIColor clearColor];
            downloadButton.userInteractionEnabled = YES;
            downloadButton.highlighted = YES;
            [cell.contentView addSubview:downloadButton];
      }    
        NSString *titleLabel = [[appDelegate getBookNames]objectAtIndex:indexPath.row];
        cell.TitleLabel.text = titleLabel;


        return cell;
    }

    -(void)downloadButtonClicked:(id)sender{

    }
4

3 回答 3

3

在按钮操作中,您可以通过访问 superView 来获取单元格

-(void)downloadButtonClicked:(id)sender{
    UIButton *button = (UIButton*)sender;
    UIView *view = button.superview; //Cell contentView
    UITableViewCell *cell = (UITableViewCell *)view.superview;
    cell.textLabel.text; //Cell Text
}
于 2012-06-26T07:35:30.747 回答
1
first set the tag of your label say it is 100.

//in the button click method...

UITableViewCell *cell = (UITableViewCell *)[[button superview] superview];

UILabel *lbl = (UILabel *)[cell viewWithTag:100];//this is for custom label 

NSLog(@"label text =%@",lbl.text);

else  NSLog(@"label text =%@",cell.titleLabel.text);
于 2012-06-26T07:36:01.670 回答
0

当您点击表格视图单元格时,将调用 Delegate 函数,它会为您提供索引路径部分和行值。当您将按钮放在表格单元格上时,只需将标签 - indexpath.row 分配给按钮标签。在调用按钮函数时找到这个标签,并找到数组索引以获取数组上该索引的值。

于 2012-06-26T07:39:51.557 回答