【问题标题】:How to remove UIView from the superView with specific position programmatically如何以编程方式从具有特定位置的超级视图中删除 UIView
【发布时间】:2016-12-06 03:08:57
【问题描述】:

我是 swift 新手,使用 swift 3,我构建了读取一组图像的 tableview,我希望它如下所示: 当用户在表格视图中选择图像时,我将其显示在 UIImageView 中,当取消选择他已经在表格视图中选择的图像时,将其从 UIImageView 中删除(启用了多选)。我下面的代码仅适用于一个图像选择,但是如果选择了多个图像然后取消选择最后一个选择的图像,则只会从 UIImageview 中删除。所以我的问题是如何删除属于 UItableview 中取消选择记录的 UIImageview

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        image_view.image = UIImage(data: Saveddata[indexPath.row].photo as! Data)
             //create image view programmatically
            currentImageView = UIImageView(frame: CGRect(x: 130 + (i * 10), y: 50 + (i * 5), width: 50, height: 100))
             currentImageView.contentMode = .scaleAspectFit
             currentImageView.image = image_view.image
             view.addSubview(currentImageView as UIView)           
    }

 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

       currentImageView.removeFromSuperview()


    }

【问题讨论】:

  • 您不能简单地删除 UITableViewCell 中的视图或 UI 组件。它可重复用于其他行。您可以做的是使用全局数组设置一个标志,并保留indexPath.row 作为您已删除的那些的索引。然后在您的cellForRow 中,检查该索引是否出现,隐藏图像或将width 约束更改为 0
  • 避免使用 addSubview,而是使用 Storyboard 或带有 IBOutlet 的 xib。这可以防止在单元格内创建重复视图
  • @h44f33z,谢谢,但是我并没有尝试将其从 tableview 中删除,而是尝试从我创建的 UIview 中删除它,并在 tableview 中选择此图像时将图像添加到其中
  • 尝试使用tag。在下面添加了我的答案

标签: swift


【解决方案1】:

您可以根据indexPath.row 为每个UIImageView 使用tag,以便您可以通过标签引用。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let image = UIImage(data: Saveddata[indexPath.row].photo as! Data)
    //create image view programmatically
    let imageView = UIImageView(frame: CGRect(x: 130 + (i * 10), y: 50 + (i * 5), width: 50, height: 100))
    imageView.contentMode = .scaleAspectFit
    imageView.tag = 100 + indexPath.row
    imageView.image = image
    view.addSubview(imageView as UIView)
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     // get imageView by its tag        
    let deselectedImageView = view.viewWithTag(100 + indexPath.row) as! UIImageView
    deselectedImageView.removeFromSuperview()


}

【讨论】:

  • 喜欢这个想法,但它返回了一个错误:无法将类型“UIView”(0x10ea19b40)的值转换为“UIImageView”(0x10ea1b288)。
  • @rania 通过将 100 添加到标签来更新我的答案,因此它将使用标签 0
  • 天哪,感谢一百万,它现在可以工作了,我明白了。非常感谢您的帮助,一直在寻找出路很长时间
【解决方案2】:

如果您想在选择/取消选择时更新单元格外观,您应该在 UITableViewCell 子类中覆盖方法 setSelected(_:animated:),而不是尝试直接从您的 UITableViewDelegate 方法更新它:

override func setSelected(_ selected: Bool, animated: Bool) {
    // Do whatever you want depending on the selected value
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多