用于在tableView中选择随机单元格的按钮

时间:2013-07-08 06:45:12

标签: xcode uitableview button

如何在表视图上创建一个按钮,当随机触摸时选择其中一个单元格?

我知道如何添加圆形矩形按钮和所有,而不是选择随机单元格的代码部分。

谢谢!

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipe = [recipes objectAtIndex:indexPath.row];

        // Hide bottom tab bar in the detail view
        //   destViewController.hidesBottomBarWhenPushed = YES;
    }

Code

enter image description here

1 个答案:

答案 0 :(得分:0)

您好,如您在评论中提到的,您只有一个部分包含36个单元格。使用arc4random找到rendom行。

然后从部分和行中获取indexPath

然后致电didSelectRowAtIndexPath

按钮点击方法的整个代码看起来像....

int section = 0;
int row = arc4random() %35;
NSIndexPath * path = [NSIndexPath indexPathForRow:row inSection:section];
if ([self.yourTableView.delegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) {
    [self.yourTableView.delegate tableView:self.yourTableView willSelectRowAtIndexPath:path];
}

[self.yourTableView selectRowAtIndexPath:path animated:YES scrollPosition: UITableViewScrollPositionNone];    

if ([self.yourTableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
    [self.yourTableView.delegate tableView:self.yourTableView didSelectRowAtIndexPath:path];
}

然后实施didSelectRowAtIndexPath

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
     btn.tag = indexPath.row;
     [self performSegueWithIdentifier:@"showRecipeDetail" sender:btn];
}

确保您在viewDidLoad

中编写了以下代码
self.yourTableView.delegate = self;
self.yourTableView.dataSource = self;

并按以下方式更改prepareForSegue方法

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showRecipeDetail"]) {

        RecipeDetailViewController *destViewController = [segue destinationViewController];

        NSInteger tagIndex = [(UIButton *)sender tag];

        destViewController.recipe = [recipes objectAtIndex:tagIndex];
    }
}

这肯定会帮助你.....