Swift 4 委托(delegate)和传递文本字段数据

标签 swift delegates

我正在尝试使用 GoogleBooks API 制作一个应用程序,我可以在其中使用标题或作者或两者来搜索书籍。我目前正在处理委托(delegate)部分,以便能够将搜索词传递给结果 TableView 。但是,我在使用 let 常量的变量时遇到错误,但我将它们声明为 var,所以我不确定我在哪里搞砸了。

这是带有两个搜索框和按钮的 View 的 UIViewController 代码:

import UIKit

protocol ViewControllerDelegate: class {
    func searchInput(_ titleFromSearch: String?, authorFromSearch: String?)
}

class ViewController: UIViewController {
    @IBOutlet weak var titleFromSearch: UITextField!
    @IBOutlet weak var authorFromSearch: UITextField!

    weak var delegate: ViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        titleFromSearch.delegate = self
        authorFromSearch.delegate = self
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event:
        UIEvent?) {
        super.touchesEnded(touches, with: event)
        titleFromSearch.resignFirstResponder()
        authorFromSearch.resignFirstResponder()
    }
}

extension ViewController: UITextFieldDelegate {
    func fieldsDidEndEditing(_ titleEntered: UITextField, authorEntered:
        UITextField) {
        if let delegateController = delegate {
            delegateController.searchInput(titleFromSearch.text,
                                           authorFromSearch: authorFromSearch.text)
        }
    }
}

这是我为显示结果而设置的 TableViewController 的代码。

import UIKit
import GoogleBooksApiClient

class SearchResultsTableViewController: UITableViewController {
    var titleFromSearch: String?
    var authorFromSearch: String?

    var data = [Volume]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let session = URLSession.shared
        let client = GoogleBooksApiClient(session: session)

        let req = GoogleBooksApi.VolumeRequest.List(query: "Google")

        let task: URLSessionDataTask = client.invoke(
            req,
            onSuccess: { [weak self] volumes in
                self?.data = volumes.items
                self?.tableView.reloadData()
            },
            onError: { error in
                print("\(error)") }
        )
        task.resume()
    }

    // MARK: - Table view data source

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt
        indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",
                                                 for: indexPath)

        let item = data[indexPath.row]
        cell.textLabel?.text = item.volumeInfo.title
        cell.detailTextLabel?.text = item.volumeInfo.authors.first

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        if let destination = segue.destination as? ViewController {
            destination.delegate = self
        }
    }
}

这里是我得到 let constant error is with these two assignment statements:

extension SearchResultsTableViewController: ViewControllerDelegate {
    func searchInput(_ titleFromSearch: String?, authorFromSearch: String?)
    {
        titleFromSearch = titleFromSearch
        authorFromSearch = authorFromSearch
    }
}

我添加了所有代码,因为正如我所说,我是 iOS 的新手,我不确定代码中此错误的来源。

最佳答案

在导致错误的两行中:

titleFromSearch = titleFromSearch
authorFromSearch = authorFromSearch

您正在尝试将参数分配给自己。您想要将参数值设置为您的同名属性。为此,将 self. 添加到属性引用中:

self.titleFromSearch = titleFromSearch
self.authorFromSearch = authorFromSearch

关于Swift 4 委托(delegate)和传递文本字段数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978982/

相关文章:

ios - 如果我返回 Swift,如何在 View 中移动而无需再次重新加载它们

c# - 如何调用 Delegate.Target 的 .Invoke 方法?

c# - 不能通过委托(delegate)

ios - 在多个类中定义相同的协议(protocol)

C# 从 MethodInfo 获取委托(delegate)

ios - Swift 中多个过滤器的 Firebase 查询

ios - NSUserDefaults.standardUserDefaults().stringForKey ("useremail") 值返回 null

delegates - QML 独特的 TableViewColumn 委托(delegate)

ios - 快速将数组转换为 JSON 字符串

swift - swift 中这两个枚举声明有什么区别?