【问题标题】:Self is nil when finding cell index path查找单元格索引路径时,self 为 nil
【发布时间】:2019-04-14 14:36:01
【问题描述】:

我有这个使用表格视图的应用程序,并且每个表格视图单元格、cellTitle 和 cellDescription 中有两个文本字段。我想知道当任一文本字段被编辑时单元格的索引路径是什么。我必须将该数据传递给 viewController,以便我可以将该数据保存在我的单元格数组中。当我每次测试运行它时,self 为 nil,这会停止代码并且我找不到让 viewController 知道已编辑的单元格编号的方法。有人可以帮我找到已编辑文本字段单元格的单元格 indexPath 吗?

DashboardCell.swift

import UIKit
protocol cellInfoDelegate {
    func tableCellInfo(title: String?, description: String?, cell: DashboardCell)

}

class DashboardCell: UITableViewCell {

    var indexpathInstance = IndexPath()

    //MARK: Outlets

    @IBOutlet weak var cellTitle: UITextField!

    @IBOutlet weak var cellDescription: UITextField!

    @IBAction func cellTitleEdited(_ sender: Any) {


        if cellTitle.text != nil {
            // ERROR HERE: self is nil
            cellInformationDelegate.tableCellInfo(title: cellTitle.text, description: cellDescription.text, cell: self)
        } else {
            cellTitle.text = "Untitled"
            cellInformationDelegate.tableCellInfo(title: cellTitle.text, description: cellDescription.text, cell: self)
        }


            }



    @IBAction func cellDescriptionEdited(_ sender: Any) {
        if cellDescription.text != nil  {
            cellInformationDelegate.tableCellInfo(title: cellTitle.text, description: cellDescription.text, cell: self)
        } else {
            cellDescription.text = "Add a description Here"
            cellInformationDelegate.tableCellInfo(title: cellTitle.text, description: cellDescription.text, cell: self)
        }
    }

    let cellInformationDelegate: cellInfoDelegate! = nil


    func setDashboardCell (cell: Dashboard) {
        cellTitle.text = cell.title
        cellDescription.text = cell.desccription
    }






}

DashboardViewcontroller.swift

import UIKit

class DashboardViewController: UIViewController, cellInfoDelegate, UITableViewDataSource, UITableViewDelegate  {

    var events: [Dashboard] = []

    @IBOutlet weak var DashboardAdd: UIButton!
    @IBOutlet weak var tableView: UITableView!    
    @IBAction func DashboardAddA(_ sender: Any) {
        events.append(Dashboard(title: "Untitled", description: "Add A Description Here"))
        tableView.reloadData()
    }



    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        self.hideKeyboardWhenTappedAround()
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return events.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let Dcells = events[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "DashboardCell") as! DashboardCell
        cell.setDashboardCell(cell: Dcells)
        return cell
    }


    func tableCellInfo(title: String?, description: String?, cell: DashboardCell) {
        let indexPath = (self.tableView.indexPath(for: cell)?.row)!
        print("At row \(indexPath), the title is \(title), and the description is \(description)")

        if title != "" && description != "" {
        events[indexPath] = Dashboard(title: (title)!, description: (description)!)
        } else if title != "" && description == "" {
            events[indexPath] = Dashboard(title: (title)!, description: "")

        } else if title == "" && description != "" {
            events[indexPath] = Dashboard(title: "", description: (description)!)

        } else {
            events[indexPath] = Dashboard(title: "", description: "")

        }
    }


    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
        }

    func getCellNumber (cell: DashboardCell) -> Int?{
        let indexPath = self.tableView.indexPath(for: cell)
        return indexPath?.row
    }

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer =     UITapGestureRecognizer(target: self, action:    #selector(self.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }



}

【问题讨论】:

  • Delegate 必须是一个弱属性。改让cellInformationDelegate:cellInfoDelegate!到弱 var cellInformationDelegate: cellInfoDelegate?此外,您忘记设置委托属性。之后 let cell = tableView.dequeueReusableCell(withIdentifier: "DashboardCell") 为! DashboardCell 添加单元格。 cellInformationDelegate = self

标签: ios swift tableview


【解决方案1】:

首先,你需要改变

let cellInformationDelegate: cellInfoDelegate! = nil

到:

var cellInformationDelegate: cellInfoDelegate! = nil

然后您需要在 (cellForRowAt indexPath:) 中设置委托(请原谅伪代码):

cell.cellInformationDelegate = self

您忘记设置委托,因此未调用委托方法。而且您也没有设置 indexPath。所以你还需要添加:

cell.indexPathInstance = indexPath

【讨论】:

  • cellInformationDelegate 不应使用! 声明。并且单元格不应该有自己的索引路径属性。单元永远不需要知道自己的索引路径。
  • @rmaddy 我不会说永远不会?如果您需要知道包含调用委托方法的文本字段的单元格的 indexPath 怎么办?我已经看过很多次了,老实说,有时我自己也用过。你会怎么做?是的,那里不需要 bang 运算符,因为它被设置为 nil,但也许他不希望它作为一个可选项,也不想稍后解开
  • 为什么单元格需要知道文本字段的索引路径?最大的问题是如果可以插入、删除或移动行,则索引路径可能是错误的。
  • @rmaddy 是的,我肯定在那里看到了问题。那么跟踪 indexPath 的最佳解决方案是什么?这是出于好奇。我的回答是基于他的问题,即不要重写他的代码。
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2023-03-11
相关资源
最近更新 更多