我在将“用户选择的”图像分配给 tableViewCells 和 tableview 背景时遇到问题。我收到错误“无法分配“UIImage”类型的值?输入“UIView?”。
外汇。当我编写以下内容时,尝试获取用户选择的图像,显示在特定单元格中:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Diary1", for: indexPath)
cell.textLabel?.text = allDiaries[indexPath.row].diaryName
cell.detailTextLabel?.text = allDiaries[indexPath.row].diaryQuestion
cell.backgroundView = UIImage(data: newDiary?.diaryTheme ?? Data())
return cell
}
在另一个地方,我在编写此内容时遇到了相同的错误:
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundView = UIImage(data: (newDiary?.diaryTheme ?? Data()))
}
所以我想在使用 tableView 背景时,您必须知道如何从 UIImageView 转换为 UIView。
有人知道怎么做吗?
谢谢!
最佳答案
您需要创建一个包含 UIImage
的 UIImageView
实例,然后将该 imageView 设置为 backgroundView
属性,这将起作用,因为 UIImageView
是 UIView
的子类。
let imageView = UIImageView(image: UIImage(data: (newDiary?.diaryTheme ?? Data())))
tableView.backgroundView = imageView
然后在 cellForRowAt
中执行相同操作(请记住,我将 newDiary
更改为 allDiaries[indexPath.row]
,因为您会得到否则所有单元格的背景图像相同):
let imageView = UIImageView(image: UIImage(data: allDiaries[indexPath.row].diaryTheme)
cell.backgroundView = imageView
关于ios - 如何将类型 'UIImage?' 的值分配给类型 'UIView?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154108/