无法将自定义单元格与UITableView一起使用

时间:2018-09-12 06:51:42

标签: ios swift xcode

我正在尝试使用自定义填充uitableview,但出现以下错误:

Fatal error: Use of unimplemented initializer 'init(style:reuseIdentifier:)' for class 'Appname.PostCellView'

代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PostCellView
        return cell
    }

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(PostCellView.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

后视图单元格:(此类已加载到视图的文件所有者中)

import UIKit
protocol PostCellViewDelegate: class {

}

class PostCellView: UITableViewCell {
    weak var delegate:  PostCellViewDelegate?


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        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

    }

}

请帮助我查找我的代码有什么问题以及如何纠正该代码。

2 个答案:

答案 0 :(得分:0)

请将对commonInitialization()的调用从initWithCoder转移到方法awakeFromNib。同时删除initWithCoder方法

在您的PostCellView代码中,添加此方法并删除initWithCoder。

override func awakeFromNib() {
  super.awakeFromNib()
  let _ = commonInitialization()
}

答案 1 :(得分:0)

覆盖init(style:reuseIdentifier:)

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    // Code
}

请选中此tutorial