코드 사용자 정의 Cell(사용자 정의 Cell이 제대로 표시되지 않음 및 fatal error:unexpectedly found nil)

3854 단어
선상 부호
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //             。
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellIDForCodeCustomCell", for: indexPath) as! CodeCustomCell
    // Configure the cell...
    cell.configure(modelData: (modelData?[indexPath.row])!) // fatal error: unexpectedly found nil while unwrapping an Optional value
    return cell
}

두 가지 오류:
1. fatal error: unexpectedly found nil while unwrapping an Optional value(           )
2.      cell  ,View               cell

위의 코드가 정상적으로 작동하지 않습니다.알고 있는 것은:
  • dequeue Reusable Cell은 시스템이 효율을 높이기 위한 방법이다.구체적으로 버퍼 안에서 이 셀이 있는지 없는지 확인해 보세요.없으면 다시 초기화해. 이렇게.
  • 뒤의 코드 운행에 문제가 없습니다.
  • 그리고 관련 문장을 몇 편 봤어요.dequeue Reusable Cell 버퍼에서 뭐 찾는 거 말고 다른 거 했다고요?
  • Swift의 구조기 해석 init와 사용자 정의cell의 문제
  • - 셀 다시 쓰기 질문
  • 첫 번째 문장의 말을 인용하다.
  • 지정 구조기는 직접 부류의 지정 구조기 방법을 사용해야 한다.
  • 편의구조기는 같은 종류에 정의된 다른 초기화 방법을 사용해야 한다.
  • 편리한 구조기는 마지막에 지정된 구조기를 호출해야 한다.

  • UItable ViewCell을 다시 쓰기 위한 prepare ForReuse를 참조하십시오.
    cell을 다시 사용하는 메커니즘은 버퍼를 이용하여 다시 사용할 수 있는cell을 저장하고cell을 표시할 때 먼저 버퍼에서 꺼내는 것이다. 만약에 버퍼에 이런cell이 없다면 다시 사용할 수 있는cell이 없으면 이때cell을 다시 초기화하고 버퍼에 추가한다.
    다음과 같은 몇 가지 문제가 해결되었습니다.
  • 하나는 Swift의 몇 개의 init 구조기의 관계라는 문제에서 네 번째는 대응하는 해석
  • 이다.
  • 또 하나는 공식 문서에서 강조한 등록해야 할 문제다.

  • 수정된 코드를 붙이다.
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(CodeCustomCell.self, forCellReuseIdentifier: "CellIDForCodeCustomCell")
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellIDForCodeCustomCell", for: indexPath) as UITableViewCell
        // Configure the cell...
        (cell as! CodeCustomCell).configure(modelData: (modelData![indexPath.row])!)
        return cell
    }
    
    class CodeCustomCell: UITableViewCell{
        var _imageView:UIImageView!
        var label1:UILabel!
        var label2:UILabel!
        var label3:UILabel!
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            _imageView = UIImageView(frame: CGRect(x: 50, y: 0, width: 88, height: 88))
            label1 = UILabel(frame: CGRect(x: 0, y: 0, width: 42, height: 21))
            label2 = UILabel(frame: CGRect(x: 0, y: 29, width: 42, height: 21))
            label3 = UILabel(frame: CGRect(x: 0, y: 58, width: 42, height: 21))
        }
        
        func configure(modelData:ModelData){
            label1.text = modelData.attr1
            label2.text = modelData.attr2
            label3.text = modelData.attr3
            _imageView.image = UIImage(named: modelData.imageName)
            self.addSubview(label1)
            self.addSubview(label2)
            self.addSubview(label3)
            self.addSubview(_imageView)
        }
        
        required init?(coder aDecoder: NSCoder) {
            // super.init(style: .default, reuseIdentifier: "CellIDForCodeCustomCell")
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    그리고 정상적으로 나타나지 못한 다른 원인도 말씀드리겠습니다.
  • dataSource, delegate 설정이 없음
  • storyBoard가 현재 TableViewController와 연결되지 않았습니다
  • storyBoard의cell 관련은 쓸 수도 있고 안 쓸 수도 있다
  • addSubView 없음
  • 마지막으로 Storyboard 파일, xib 파일, 코드로 직접 맞춤형 3가지 방법으로 맞춤형 Cell의 데모 링크 Three Ways ToCustom Your Cell를 첨부합니다.

    좋은 웹페이지 즐겨찾기