通过UITableViewCell上的自定义按钮更新领域

问题描述

我有一个存储在Realm中的“书”的表视图。我想在自定义UITableViewCell上单击按钮时将“ CurrentBook”属性设置为“ True”。

我相信我的错误与在“ func selectCurrentBook”中获得正确的帐面价值有关,当我使用下面的可选内容时,什么也没发生。

@objc func selectCurrentBook(sender: UIButton) {
        try! realm.write {
            book?.currentlyReading = true
        }
    }

当我不为书使用可选内容并使用book.currentlyReading = true时,出现错误“意外发现nil,同时隐式展开了可选值:”

我错误地将帐面价值传递给某个地方吗?我似乎找不到答案。也许我在委派错误?

我的TableViewCell是:

import UIKit
import RealmSwift

protocol MyBooksDelegate {
    func currentlyReadingButton()
}

class MyBooksTableViewCell: UITableViewCell {
    
    let realm = try! Realm()
    
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var authorLabel: UILabel!
    
    @IBOutlet weak var smallThumbnailImageView: UIImageView!
    
    @IBOutlet weak var currentlyReadingButton: UIButton!
    
    @IBAction func currentlyReadingButton(_ sender: Any) {

    }
    
    private var book: Book!
    
    func loadImage(smallThumbnailURL: String) {
        let imageURL = URL(string: smallThumbnailURL ?? "")
        smallThumbnailImageView.sd_setImage(with: imageURL)
        }

    func configureCell(book: Book,delegate: MyBooksDelegate?) {
       titleLabel.text = book.bookTitle
       authorLabel.text = book.bookAuthor
        loadImage(smallThumbnailURL: book.bookSmallThumbnailImageURL)
        
        currentlyReadingButton.addTarget(self,action: #selector(selectCurrentBook(sender:)),for: .touchUpInside)
                        
    }
    
    @objc func selectCurrentBook(sender: UIButton) {
        try! realm.write {
            book?.currentlyReading = true
        }
    }
}

使用TableView的我的View Controller是:

import SwiftyJSON
import RealmSwift

class BooksViewController: UIViewController,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate {
    
    
    @IBOutlet weak var myBooksTableView: UITableView!
    
    let realm = try! Realm()
    
    var books: Results<Book>?
    
    // Search Bar Properties
    var searchParameter = "intitle"
    
    var booksArray: [Book] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadBooks()
        // Setting up the TableView
               self.myBooksTableView.delegate = self
               self.myBooksTableView.dataSource = self
               self.myBooksTableView.rowHeight = 120.0
        
        // Setup Title
        title = "My Books"
       // navigationController?.navigationBar.prefersLargeTitles = true

    }
    
    override func viewWillAppear(_ animated: Bool) {
         navigationController?.navigationBar.barStyle = .black
        loadBooks()
     }
    
    func loadBooks() {
        books = realm.objects(Book.self).sorted(byKeyPath: "DateCreated",ascending: false)
        myBooksTableView.reloadData()
    }

    // TABLEVIEW
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return books?.count ?? 1
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell",for: indexPath) as? MyBooksTableViewCell {
            cell.configureCell(book: (books?[indexPath.row])!,delegate: self as? MyBooksDelegate)
     //       cell.selectionStyle = UITableViewCell.SelectionStyle.none

            return cell
        } else {
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView,canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "myBooksTOMyBooksDetail",sender: self)
        myBooksTableView.deselectRow(at: indexPath,animated: true)
    }

我的书本模型是:

class Book: Object {
    @objc dynamic var bookTitle: String!
    @objc dynamic var bookAuthor: String!
    @objc dynamic var bookSmallThumbnailImageURL: String!
    @objc dynamic var bookThumbnailImageURL: String!
    @objc dynamic var bookDescription: String!
    @objc dynamic var bookISBN_13: String!
    @objc dynamic var currentlyReading = false
    @objc dynamic var DateCreated = Date()
    @objc dynamic var WordID = UUID().uuidString
    
    // words
    let words = List<Word>()
    
    override static func primaryKey() -> String? {
        return "WordID"
    }
}

enter image description here

enter image description here

enter image description here

解决方法

最兼容的语法是

currentlyReadingButton.addTarget(self,action: #selector(selectCurrentBook),for: .touchUpInside)

@objc func selectCurrentBook(_ sender: UIButton) {

无论如何,尽管单元格是自定义的,我还是希望IBAction胜过目标/动作

协议MyBooksDelegate似乎未使用。


旁注:

强行打开单元格

let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell",for: indexPath) as! MyBooksTableViewCell

崩溃(包含报告)揭示了一个设计错误,该错误可以立即得到解决。使用if let,您什么也看不到,也不知道为什么。


更新:

发生崩溃是因为您没有在单元格中设置book,而是在{之后添加第一行

func configureCell(book: Book,delegate: MyBooksDelegate?) {
   self.book = book
   titleLabel.text = book.bookTitle
   ...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...