我有一个
UITableView
,并且我还定义了它的子类以在每个单元格中包含一个按钮。@objc
函数(因为我是以编程方式执行的)。
我可以看到表格单元格以及其中可见的按钮,因为我已经在我的
viewDidLoad
类的 UIViewController
函数中注册了它,但是当我单击它时它没有响应。我期待在控制台中打印一条消息
@objc func actbuttonFuncCall(_ sender: UIButton) {
print("button clicked")
}
这就是我为
tableView
部分定义 cellForRowAt
函数的方式:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) as! MyCustomCell
if let model = viewsArray[indexPath.row] {
// name assinged from another VC
cell.textLabel?.text = model.name
cell.textLabel?.textColor = .systemPink
cell.button.isUserInteractionEnabled = true
cell.isUserInteractionEnabled = true
cell.button.addTarget(self, action: #selector(actbuttonFuncCall), for: .touchUpInside)
}
return cell
}
这是我的
UIButton
的子类
class MyCustomCell: UITableViewCell {
let button = UIButton()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
button.setTitle("Get to it", for: .normal)
button.backgroundColor = .blue
addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerYAnchor.constraint(equalTo: centerYAnchor),
button.centerXAnchor.constraint(equalTo: centerXAnchor),
button.widthAnchor.constraint(equalToConstant: 100), // Adjust as needed
button.heightAnchor.constraint(equalToConstant: 40) // Adjust as needed
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我还应该执行任何其他操作才能使按钮功能正常工作吗?
正如 @HangaRash 在他们的评论中所说,您应该在单元格的 contentView 中添加按钮,它将是:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
...
//addSubview(button)
contentView.addSubview(button)
}
这与视图层次结构不同:
UITableView
|---MyCustomCell
|--- UIButton (Get to it)
|--- UITableViewCellContentView
//The button is below UITableViewCellContentView so the cell
//will receive touch event from `didSelectRowAt` delegate.
UITableView
|---MyCustomCell
|--- UITableViewCellContentView
|--- UIButton (Get to it)
//The button is above UITableViewCellContentView so the cell
//will receive touch event from UIButton's first if within its frame.
//And receives `didSelectRowAt` delegate if out of button frame.