如何在表视图上创建一个按钮,当随机触摸时选择其中一个单元格?
我知道如何添加圆形矩形按钮和所有,而不是选择随机单元格的代码部分。
谢谢!
- (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;
}
答案 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];
}
}
这肯定会帮助你.....