Swift 4 tableview 使用通用完成处理程序不显示数据
Swift 4 tableview not showing data using generic completion handler
我在使用通用函数的完成处理程序时遇到问题,似乎它不会在 UITableView
上传递任何内容,除非我在其上放置一些断点,请检查下面的代码:
public func requestGenericData<T: Decodable>(urlString: String, httpMethod: String?, token: String!, completion: @escaping(T) ->()) {
let fullStringUrl = url + urlString
guard let url = URL(string: fullStringUrl) else { return }
guard let token = token else { return }
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/json", forHTTPHeaderField: "accept")
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
urlRequest.httpMethod = httpMethod
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if self.isInternetAvailable() {
guard let data = data else { return }
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 {
do {
let obj = try JSONDecoder().decode(T.self, from: data)
completion(obj)
} catch {
print("Error: \(String(describing: error))\n StatusCode: \(httpResponse.statusCode)")
}
}
}
} else {
showAlert(title: "No Internet Connect", message: "Please open your network and try again.", alertStyle: .alert, buttonTitle: "OK", buttonStyle: .default)
return
}
}.resume()
}
这是将在下面的 table 查看代码中显示其结果列表的函数:
func listOfServicesMenus() {
var jobsInCategory = [String]()
apiHelper.requestGenericData(urlString: "nothing/more/than/a/noob", httpMethod: "GET", token: token) { (noobs: Noobs) in
for job in jobs.jobCategories {
jobsInCategory.append(job.name)
for jobDetails in job.getJobs {
jobsInCategory.append(jobDetails.name)
}
}
self.listOfServices.dropView.dropDownOptions = jobsInCategory
}
}
swift 的新手和开发中的 iOS,似乎每当我在其上设置断点时它似乎工作正常,但是如果不在其上,它不显示任何内容?
有没有人知道如何使用泛型实现正确的完成处理程序,或者我在尝试编写这段代码时遗漏了什么?
感谢那些帮助我摆脱困境的人。
更新
我使用 UIView
、UITableViewDelegate
、UITableViewDataSource
、UITableView
创建了一个所谓的 DropDownMenu
(这是在 UIView
下创建的,用于正确处理约束).
更新 2
添加了 UITableView
的实现(在 UIView
下)
class dropDownView: UIView, UITableViewDelegate, UITableViewDataSource {
var dropDownOptions = [String]()
var tableView = UITableView()
var delegate: DropDownDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.backgroundColor = UIColor.clear.cgColor
self.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.layer.cornerRadius = 10
tableView.backgroundColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
self.addSubview(tableView)
tableView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let cell = UITableViewCell()
cell.contentView.backgroundColor = UIColor.clear
return dropDownOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = dropDownOptions[indexPath.row]
cell.textLabel?.textColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
cell.layer.borderColor = UIColor(displayP3Red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0).cgColor
cell.backgroundColor = UIColor(displayP3Red: 254/255, green: 252/255, blue: 215/255, alpha: 1.0)
cell.selectionStyle = .none
cell.textLabel?.textAlignment = .center
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor(displayP3Red: 133/255, green: 178/255, blue: 56/255, alpha: 1.0)
selectedCell.textLabel?.textColor = UIColor.white
self.delegate.dropDownPressed(string: self.dropDownOptions[indexPath.row])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: (indexPath))!
cellToDeSelect.contentView.layer.borderColor = UIColor(displayP3Red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0).cgColor
cellToDeSelect.contentView.backgroundColor = UIColor(displayP3Red: 254/255, green: 252/255, blue: 215/255, alpha: 1.0)
cellToDeSelect.textLabel?.textColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.contentView.backgroundColor = UIColor.clear
}
感谢您 Anil Varghese,创建了另一个将在 dropDownView
class 下重新加载数据的函数并添加了这行代码:
func reloadData() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
我在使用通用函数的完成处理程序时遇到问题,似乎它不会在 UITableView
上传递任何内容,除非我在其上放置一些断点,请检查下面的代码:
public func requestGenericData<T: Decodable>(urlString: String, httpMethod: String?, token: String!, completion: @escaping(T) ->()) {
let fullStringUrl = url + urlString
guard let url = URL(string: fullStringUrl) else { return }
guard let token = token else { return }
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/json", forHTTPHeaderField: "accept")
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
urlRequest.httpMethod = httpMethod
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if self.isInternetAvailable() {
guard let data = data else { return }
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 {
do {
let obj = try JSONDecoder().decode(T.self, from: data)
completion(obj)
} catch {
print("Error: \(String(describing: error))\n StatusCode: \(httpResponse.statusCode)")
}
}
}
} else {
showAlert(title: "No Internet Connect", message: "Please open your network and try again.", alertStyle: .alert, buttonTitle: "OK", buttonStyle: .default)
return
}
}.resume()
}
这是将在下面的 table 查看代码中显示其结果列表的函数:
func listOfServicesMenus() {
var jobsInCategory = [String]()
apiHelper.requestGenericData(urlString: "nothing/more/than/a/noob", httpMethod: "GET", token: token) { (noobs: Noobs) in
for job in jobs.jobCategories {
jobsInCategory.append(job.name)
for jobDetails in job.getJobs {
jobsInCategory.append(jobDetails.name)
}
}
self.listOfServices.dropView.dropDownOptions = jobsInCategory
}
}
swift 的新手和开发中的 iOS,似乎每当我在其上设置断点时它似乎工作正常,但是如果不在其上,它不显示任何内容?
有没有人知道如何使用泛型实现正确的完成处理程序,或者我在尝试编写这段代码时遗漏了什么?
感谢那些帮助我摆脱困境的人。
更新
我使用 UIView
、UITableViewDelegate
、UITableViewDataSource
、UITableView
创建了一个所谓的 DropDownMenu
(这是在 UIView
下创建的,用于正确处理约束).
更新 2
添加了 UITableView
的实现(在 UIView
下)
class dropDownView: UIView, UITableViewDelegate, UITableViewDataSource {
var dropDownOptions = [String]()
var tableView = UITableView()
var delegate: DropDownDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.backgroundColor = UIColor.clear.cgColor
self.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.layer.cornerRadius = 10
tableView.backgroundColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
self.addSubview(tableView)
tableView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let cell = UITableViewCell()
cell.contentView.backgroundColor = UIColor.clear
return dropDownOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = dropDownOptions[indexPath.row]
cell.textLabel?.textColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
cell.layer.borderColor = UIColor(displayP3Red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0).cgColor
cell.backgroundColor = UIColor(displayP3Red: 254/255, green: 252/255, blue: 215/255, alpha: 1.0)
cell.selectionStyle = .none
cell.textLabel?.textAlignment = .center
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor(displayP3Red: 133/255, green: 178/255, blue: 56/255, alpha: 1.0)
selectedCell.textLabel?.textColor = UIColor.white
self.delegate.dropDownPressed(string: self.dropDownOptions[indexPath.row])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: (indexPath))!
cellToDeSelect.contentView.layer.borderColor = UIColor(displayP3Red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0).cgColor
cellToDeSelect.contentView.backgroundColor = UIColor(displayP3Red: 254/255, green: 252/255, blue: 215/255, alpha: 1.0)
cellToDeSelect.textLabel?.textColor = UIColor(displayP3Red: 166/255, green: 203/255, blue: 69/255, alpha: 1.0)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.contentView.backgroundColor = UIColor.clear
}
感谢您 Anil Varghese,创建了另一个将在 dropDownView
class 下重新加载数据的函数并添加了这行代码:
func reloadData() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}