ios - 如何修复条件绑定(bind)的初始化程序必须具有可选类型,而不是 'String' ?

标签 ios swift

如何解决这个问题? 条件绑定(bind)的初始化程序必须具有可选类型,而不是“String”

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

    cell.lblNamnEfternamn.text = personsArray[indexPath.row].wholeName
    cell.lblEmail.text = personsArray[indexPath.row].email
    cell.imageAvatar.image = UIImage(named: "avatar")

    if let newProfileImageUrl = personsArray[indexPath.row].profileImageUrl {
        let url = NSURL(string: newProfileImageUrl)
        let request = URLRequest(url: url! as URL)
        let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                cell.imageAvatar.image = UIImage(data: data!)
                tableView.reloadData()
            }

        }
    }
    return cell
}

enter image description here

最佳答案

替换这个

if let newProfileImageUrl = personsArray[indexPath.row].profileImageUrl {

let newProfileImageUrl = personsArray[indexPath.row].profileImageUrl 

此外,最好使用 SDWebImage

cell.imageAvatar.sd_setImage(with: URL(string:newProfileImageUrl), placeholderImage: UIImage(named: "placeholder.png"))

而不是每次滚动时重复获取图像

关于ios - 如何修复条件绑定(bind)的初始化程序必须具有可选类型,而不是 'String' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55419596/

相关文章:

iOS从应用程序内转到设置应用程序

ios - 保存核心数据?

ios - NSURLSessionDataTask 是否在后台暂停?

xcode - 隐藏 UICollectionViewCell 中的 View

iphone - 尝试在设备上运行测试时出现奇怪的错误

ios - Swift:将处理程序从单击切换到双击会导致 EXC_BAD_ACCESS 异常

xcode - 将 Double 打印为 Int - 如果不是 Double 值

ios - 在分段控件中向 TableView 添加数据的问题

ios - 将 UITapGestureRecognizer 添加到 XIB

ios - 删除单元格和标题之间的空间