我有一个自定义的 UITableViewCell 子类,我在其中将两个按钮放在单元格中,我希望它们都可以点击,但到目前为止我什至无法触发任何类型的点击(除了行选择,但我在我的UITableViewController 的子类)。 Basically When one of two buttons is selected, it should remove those two buttons and update what is in the cell with a list of selectable choices (also buttons).我正在以编程方式做所有事情(没有 IB)。
My TableViewCell with Initial Two Buttons
我环顾四周,没有发现任何东西可以在 tableViewCell 中处理多个按钮。目前我一直在尝试将目标添加到我的 UITableViewCell 的 awakeFromNib() 中的按钮:
for button in initialChoiceButtons{
button.isUserInteractionEnabled = true
button.addTarget(self, action: #selector(initialChoicePressed(sender:)), for: UIControlEvents.touchUpInside)
}
我尝试过的一件事是在 cellForRowAt 的 tableView 中为我的自定义单元格将我的按钮放在单元格的前面:
for button in (cell as! FormDropDownTableViewCell).initialChoiceButtons{
cell.bringSubview(toFront: button)
}
我真的很难过,觉得这应该很容易。我即将在 scrollview 内部使用 stackView 来处理所有事情......
最佳答案
好吧,我想出了一个比较干净的方法来分离我的 tableviewcell 中的按钮点击,通过创建一个委托(delegate)协议(protocol),该协议(protocol)包含一个函数,我将从我的 tableviewcontroller 中的目标为我的 tableviewcell 中的每个按钮调用该函数。
protocol UIButtonSelectorDelegate{
func handleTap(button:DelegatingButton) //will select different functions based on DelegatingButton.actionType
}
class DelegatingButton:UIButton{
var selectorDelegate:UIButtonSelectorDelegate?
var actionType:String = "default"
}
在我的 FormDropDownTableViewCell 中,我符合 UIButtonSelectedDelegate 并像这样实现 handleTap:
func handleTap(button:DelegatingButton){
switch button.actionType{
case "initialChoiceSelect":
initialChoicePressed(initialChoice:button) //specific method for certain button.actionType also in my FormDropDownTableViewCell
case "cardTypeSelect":
cardTypeSelected(selectedCardType:button)
default:
break
}
}
现在我在我的 tableviewcontroller 中为 cellForRowAt 中的每个按钮添加目标操作,如下所示:
button.addTarget(self, action: #selector(handleButtonTaps), for: UIControlEvents.touchUpInside)
tableviewcontroller 中的 handleButtonTaps 函数很简单:
func handleButtonTaps(sender: DelegatingButton){
sender.selectorDelegate?.handleTap(button: sender)
}
喜欢自言自语 =P ..
关于ios - 在自定义 UITableViewCell Swift 中点击多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46436009/