ios 如何使用给定的参数将这个Void返回类型函数作为方法调用?

ni65a41a  于 2022-12-15  发布在  iOS
关注(0)|答案(1)|浏览(105)

这感觉像是一个简单的错误,我只是不理解。我试图调用cell.profileImageView(UIImageView)上的downloadImage()函数,但我收到一个错误,说明:
无法转换类型'的值(状态:布尔值,图像:UIImageView?)“更改为预期的参数类型”((状态:布尔值,图像:UI图像视图?))-〉无效'
如何将downloadImage()作为cell.profileImageView.downloadImage()的方法调用?downloadImage()函数和tableView()函数包含错误发生的位置,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "EmployeeTableViewCell", for: indexPath) as! EmployeeTableViewCell
        let employeeData = viewModel.employees[indexPath.row]
        cell.nameLabel.text = employeeData.fullName
        cell.teamLabel.text = employeeData.teamName + " Team"
        cell.emailLabel.text = employeeData.emailAddress
//        if employeeData.smallPhotoUrl != nil {
//            cell.profileImageView.(urlString: employeeData.smallPhotoUrl!)
//        }
//        cell.profileImageView.downloadImage(URLString: employeeData.smallPhotoUrl)
        cell.profileImageView!.downloadImage(from: employeeData.smallPhotoUrl!, with: ((status: true, image: cell.profileImageView!)))
        
        return cell
    }
func downloadImage(from URLString: String, with completionHandler: @escaping (_ response: (status: Bool, image: UIImageView? ) ) -> Void) {
        guard let url = URL(string: URLString) else {
            completionHandler((status: false, image: nil))
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard error == nil else {
                completionHandler((status: false, image: nil))
                return
            }
            
            guard let httpURLResponse = response as? HTTPURLResponse,
                  httpURLResponse.statusCode == 200,
                  let data = data else {
                completionHandler((status: false, image: nil))
                return
            }
            
            let image = UIImageView()
            completionHandler((status: true, image: image))
        }.resume()
    }
}
uwopmtnx

uwopmtnx1#

首先,完成处理程序不是用来向方法传递数据的,它是用来在方法完成工作后从方法调用中检索数据的,所以你可以这样调用它:

cell.profileImageView!.downloadImage(
   from: employeeData.smallPhotoUrl!, 
   with: { status, image in
      /// Do what you want with the status or the image values
})

例如,当您从downloadImage方法调用completionHandler((status: false, image: nil))时,在上面的代码中,status将为false,image将为nil。
据我所知,这里不需要一个完成处理程序,只需要一个方法来将图像设置为图像视图,所以将实现改为这样可能对你有用:

func downloadImage(from URLString: String, to imageView: UIImageView) {
   /// Download the image as you do and once you get the data value
   imageView.image = UIImage(data: data)
}

然后,您可以下载映像并进行如下设置:

cell.downloadImage(from: employeeData.smallPhotoUrl!, to: cell.profileImageView!)

相关问题