首页 > 解决方案 > 无法将自定义单元格与 UITableView 一起使用

问题描述

我正在尝试使用自定义填充 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.
    }

Post View Cell:(这个类被加载到视图的File's Owner中)

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

    }

}

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

标签: iosswiftxcode

解决方案


覆盖init(style:reuseIdentifier:)

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

请查看本教程


推荐阅读