ios - 如何将类型 'UIImage?' 的值分配给类型 'UIView?'

标签 ios swift uiview uiimageview tableview

我在将“用户选择的”图像分配给 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。

有人知道怎么做吗?

谢谢!

最佳答案

您需要创建一个包含 UIImageUIImageView 实例,然后将该 imageView 设置为 backgroundView 属性,这将起作用,因为 UIImageViewUIView 的子类。

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/

相关文章:

ios - 将元素附加到 Firebase 数组

ios - Pan Gesture 正在工作,但 ONTapGesture 不在 UIView 上工作

ios - 将 NSArray 对象分配给其他 NSArray 对象是否正确?

ios - 应用程序存储分配和低存储通知

ios - 单击更改 BarButtonItem 图标

iphone - 如何以编程方式向 View 添加多个标签而不用担心其 Y 位置?

objective-c - ios "Data Loading"透明背景通知

iphone - UIPickerView 与新的 UITableViewController

ios - 如何在 Xcode 中调试 EXC_BREAKPOINT (SIGTRAP)

ios - NSPredicate 对于 NSFetchedResultsController 来说太复杂了