按下UITableViewCell中的Button时的scrollToRowAtIndexPath

时间:2013-06-02 16:40:31

标签: ios objective-c uitableview uibutton

我有一个带有一些自定义单元格的tableview。第一个内部是一个按钮。按下此按钮时,我想滚动到我的tableview中的某个部分。如何将按钮操作与tableview链接?

3 个答案:

答案 0 :(得分:2)

您可以使用此功能滚动到某个部分:

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

用法的例子是:

[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:indexPath.section] 
             atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

并且对于使用tableview链接按钮操作,您可以在自定义单元格中使用协议

答案 1 :(得分:1)

从您的单元格设置一个委托机制 - 在创建单元格时,为其指定一个NSIndexPath,并在点击该按钮时将其从单元格传回。

因此,在您的UITableViewCell子类中,您将拥有:

- (IBAction)buttonPressed:(id)sender
{
     [self.delegate buttonPressedOnCellAtIndexPath:cell.indexPath]
}

返回作为委托的控制器,使用以下命令响应此方法:

- (void)buttonPressedOnCellAtIndexPath:(NSIndexPath)indexPath
{
    [self.tableView scrollToRowAtIndexPath:indexPath];
}

答案 2 :(得分:1)

您可以将单元格的按钮设置为属性,在cellForRowAtIndexPath中,您可以在加载表视图的类中设置目标,这样您就不需要任何代理。像这样:

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

       static NSString *identifier = @"YourCellIdentifier";
       YourCustomCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];
       if(cell == nil) { 
          cell = [YourCustomCell alloc/init method....
          [cell.buttonProperty addTarget:self action:@selector(cellButtonTapped:)
                                   forControlEvents:UIControlEventTouchUpInside];
       }
       //do other stuff with your cell
}

-(void)cellButtonTapped:(id)sender {
     UIButton *button = (UIButton*)sender;
     YourCustomCell *cell = (YourCustomCell*)button.superview.superview; //if the button is added to cell contentView or button.superview is added directly to the cell

    NSIndexPath *path = [yourTableView indexPathForCell:cell];
    [yourTableView scrollToRowAtIndexPath:path
                         atScrollPosition:UITableViewScrollPositionTop
                                 animated:YES];
}