0

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

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

谢谢!

- (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;
    }

代码

在此处输入图像描述

4

1 回答 1

1

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

然后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];
    }
}

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

于 2013-07-08T07:35:47.067 回答