Swift 如何在不选择整个单元格的情况下点击按钮或图像?
How to tap buttons or images without selecting the whole cell with Swift?
我在 iOS 应用程序中使用自定义 TableViewCell
。我使用方法 tableViewDidSelectRowAtIndexPath
打开一个新的 ViewController
。我需要做的是在自定义单元格中的某处添加一个按钮或图像,这样如果我点击按钮或任何元素都不会打开 ViewController
,而是在不打开单元格的情况下执行功能。
在cellForRowAtIndexPath
方法中设置[cell.button setTag:indexPath.row]
。
比addTarget
更像cell.button
[cell.button addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside]];
而不是在 yourAction
中做任何您想做的事
从发件人处获取标签。
或者你想要代码,而不是请添加你的代码,如果你是 iOS 的新手,我们可以提供更多帮助。
此代码可能对您有所帮助
这里我在 table 中使用了自定义按钮并将目标添加到该按钮
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: AnyObject = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)
// use your custom cell here
//cell = UIColor.redColor()
//cell.textLabel?!.text = String(data[indexPath.row])
//nameTextField.text = ""
let custom_btn : UIButton? = UIButton.init(type: .System)
//declaring custom button
custom_btn?.setTitle("custom button", forState: .Normal)
custom_btn!.tag = indexPath.row
custom_btn!.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
cell .addSubview(custom_btn!);
return cell as! UITableViewCell
}
func buttonClicked(sender:UIButton)
{
if(sender.tag == 5){
//Do something for tag
}
print("hello")
}
我在 iOS 应用程序中使用自定义 TableViewCell
。我使用方法 tableViewDidSelectRowAtIndexPath
打开一个新的 ViewController
。我需要做的是在自定义单元格中的某处添加一个按钮或图像,这样如果我点击按钮或任何元素都不会打开 ViewController
,而是在不打开单元格的情况下执行功能。
在cellForRowAtIndexPath
方法中设置[cell.button setTag:indexPath.row]
。
比addTarget
更像cell.button
[cell.button addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside]];
而不是在 yourAction
从发件人处获取标签。
或者你想要代码,而不是请添加你的代码,如果你是 iOS 的新手,我们可以提供更多帮助。
此代码可能对您有所帮助
这里我在 table 中使用了自定义按钮并将目标添加到该按钮
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: AnyObject = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)
// use your custom cell here
//cell = UIColor.redColor()
//cell.textLabel?!.text = String(data[indexPath.row])
//nameTextField.text = ""
let custom_btn : UIButton? = UIButton.init(type: .System)
//declaring custom button
custom_btn?.setTitle("custom button", forState: .Normal)
custom_btn!.tag = indexPath.row
custom_btn!.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
cell .addSubview(custom_btn!);
return cell as! UITableViewCell
}
func buttonClicked(sender:UIButton)
{
if(sender.tag == 5){
//Do something for tag
}
print("hello")
}