【问题标题】:How to assign value of type 'UIImage?' to type 'UIView?'如何分配“UIImage”类型的值?输入“UIView?”
【发布时间】:2019-04-08 19:05:59
【问题描述】:

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

有人知道怎么做吗?

谢谢!

【问题讨论】:

    标签: ios swift uiview uiimageview tableview


    【解决方案1】:

    您需要创建一个包含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
    

    【讨论】:

      【解决方案2】:

      您正在尝试分配UIImage,而不是UIImageView。您必须使用图像创建UIImageView,然后才能将其设置为背景视图

      cell.backgroundView = UIImageView(image:UIImage(data: newDiary?.diaryTheme ?? Data()))
      

      【讨论】:

        【解决方案3】:

        尝试使用背景颜色和图像相同。

               tableView.backgroundView.backgroundcolor = color.patterneImage(UIImage(data: (newDiary?.diaryTheme ?? Data())))
        

        【讨论】:

          【解决方案4】:

          尝试使用UIColor属性设置backgroundColorUIView

          public init(patternImage image: UIImage)
          

          代码:

          if let image = UIImage(data: newDiary?.diaryTheme ?? Data()) {
              tableView.backgroundView.backgroundColor = UIColor.init(patternImage: image)
          }
          

          在 TableViewCell 中

          if let image = UIImage(data: newDiary?.diaryTheme ?? Data()) {
              cell.backgroundView.backgroundColor = UIColor.init(patternImage: image)
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-09-25
            • 1970-01-01
            • 1970-01-01
            • 2016-12-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-02
            相关资源
            最近更新 更多