我有一个包含五行和一个按钮的UitableView。我设法创建一行的复选标记,我的意思是用户只能检查一行。当检查另一行时,前一个行未经检查。现在,有人可以帮助我如何连接我的按钮与行的选择。我尝试过但没有工作。
这是我在cellForRowAtIndexPath中的代码:
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
和我的按钮代码:
if (reloadSelectedRow==1) {
PlayViewController * controller = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil];
//controller.countdownLabel.text= score;
[self presentViewController:controller animated:YES completion:nil];
}
}
reloadSelectedRow是一个int变量,我创建它.h并在didSelectRowAtIndexPath中使用它:
reloadSelectedRow = [[NSNumber alloc] initWithInteger:indexPath.row];
问题是当我按下按钮时没有任何反应。提前谢谢。
答案 0 :(得分:3)
[YourButton addTarget:self action:@selector(ButtonPressed:) forControlEvents:UIControlEventTouchDown];
你可以像这样得到按下按钮的superView,以及索引路径:
-(void)ButtonPressed:(id)sender
{
//Get the superview from this button which will be our cell
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *pathToCell = [tableView indexPathForCell:owningCell];
}
答案 1 :(得分:1)
对于swift版本。我为每一行做了多选答案。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PersonalTestTC", for: indexPath) as! PersonalTestTC
cell.questionTitle.text = "some question here"
cell.choiceButton1.addTarget(self, action: #selector(self.choiceButtonPress), for: .touchUpInside)
cell.choiceButton2.addTarget(self, action: #selector(self.choiceButtonPress), for: .touchUpInside)
cell.choiceButton3.addTarget(self, action: #selector(self.choiceButtonPress), for: .touchUpInside)
cell.choiceButton4.addTarget(self, action: #selector(self.choiceButtonPress), for: .touchUpInside)
cell.choiceButton5.addTarget(self, action: #selector(self.choiceButtonPress), for: .touchUpInside)
cell.choiceButton1.tag = 1
cell.choiceButton2.tag = 2
cell.choiceButton3.tag = 3
cell.choiceButton4.tag = 4
cell.choiceButton5.tag = 5
return cell
}
使用标记识别
以获取选择的行和答案func choiceButtonPress(sender: UIButton){
let tbcell : UITableViewCell = sender.superview?.superview as! UITableViewCell
let getCell : IndexPath = testListTable.indexPath(for: tbcell)!
print(getCell.row)
print(sender.tag)
}
对于superview来说,这取决于UIButton你是如何处理它的。