无法在uitableview中编辑/删除顶行 - Swift

问题描述 投票:0回答:1

不确定为什么但是我的uitableview的顶行不可编辑,所有其他行正常运行并按预期删除。它就像caneditrowat indexPath:Indexpath不适用于那一行。见附图。

我在tableView(_:commit:forRowAt :)中的代码看起来像我能找到的所有教程,似乎找不到任何其他有这个问题的例子。

//MARK: Properties
    var favouriteExercises = [FavouriteExercise]()

 override func viewDidLoad() {
    super.viewDidLoad()

    //Load exercises from local DB
    if let savedFavouriteExercises = loadFavouriteExercises()
    {
        //loading exercises in from the favourites
        favouriteExercises += savedFavouriteExercises
    }

    // Use the edit button item provided by the table view controller.
    navigationItem.rightBarButtonItem = editButtonItem
}

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //count number of rows in table
    return favouriteExercises.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "FavouriteTableViewCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? FavouriteTableViewCell  else {
        fatalError("The dequeued cell is not an instance of FavouriteTableViewCell.")
    }

    // Fetches the appropriate exercise for the data source layout.
    let exercise = favouriteExercises[indexPath.row]

    //setup the layout for the cell in the table view
    cell.nameLabel.text = exercise.name
    let url = URL(string: (exercise.iconUrl))!
    cell.photoImageView.sd_setImage(with: url)
    //cell.photoImageView.image = #imageLiteral(resourceName: "defaultPhoto")
    cell.backgroundColor = UIColor.darkGray

    return cell
}

// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        favouriteExercises.remove(at: indexPath.row)
        saveFavouriteExercisess()
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

谢谢您的帮助

ios swift uitableview
1个回答
1
投票
 override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle
    {
        return UITableViewCellEditingStyle.delete
    }

答案改编自@ KumarReddy的解决方案

© www.soinside.com 2019 - 2024. All rights reserved.