我在我用作表视图中自定义单元格的视图的文件所有者中使用以下代码:
import UIKit
protocol PostCellViewDelegate: class {
func postSettingsAction()
}
class PostCellView: UITableViewCell {
weak var delegate: PostCellViewDelegate?
@IBAction func postSettingsClicked(_ sender: UIButton) {
delegate?.postSettingsAction()
print("here2")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let _ = commonInitialization()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let _ = commonInitialization()
}
func customise(imageName : String , color : UIColor, logoLabelValue : String, websiteValue: String)
{
}
func commonInitialization() -> UIView
{
let bundle = Bundle.init(for: type(of: self))
let nib = UINib(nibName: "PostCellView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
return view
}
}
,并且在具有表格视图的视图控制器中:
import UIKit
class ViewController: UIViewController, PostCellViewDelegate, UITableViewDataSource, UITableViewDelegate {
func postSettingsAction() {
print("hi there")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = PostCellView(style: UITableViewCellStyle.default , reuseIdentifier: "Cell")
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 170
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如预期的那样,单击按钮时,委托应该调用postSettingsAction(),但是不会发生。这里可能有什么问题,我该如何纠正?
答案 0 :(得分:1)
您尚未将委托分配给您的视图控制器。您需要使用tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
方法设置委托:
此外,我们在初始化单元格时应使用可重用性,
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell") as! PostCellView
将您的方法更新为:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell") as! PostCellView
cell.delegate = self // Assign delegate
return cell
}
答案 1 :(得分:1)
您需要使代表满意。只有这样,您才会被呼叫接听电话。因此添加
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = PostCellView(style: UITableViewCellStyle.default , reuseIdentifier: "Cell")
cell.delegate = self
return cell
}