从数组中删除对象的问题

时间:2017-10-04 09:37:31

标签: ios swift

我有一个UIImageView以编程方式设置,在该imageview上,我添加了一个' x'按钮(取消按钮)以编程方式进行,以便当我单击它时,特定的图像视图将消失。点击操作(在取消按钮上)我通过选择器获取。

所以,这就是我编写选择器方法的方法......

   func cancelClick() {
        imageArray.remove(at: passedIndex)
//        imageview.removeFromSuperview() //Somthing like this has to be done

}

但这不起作用。我认为还必须从superview中删除imageview,但我无法做到这一点,因为imageview的范围是本地的,必须保持这种方式来处理另一个问题。可以删除imageView的任何其他方法......?

此外,这是我填充数组和设置我的imageview的地方..

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)


        imageArray.append(image)

        for i in 0..<imageArray.count {

            // The imageview set programatically & later added to the scrollview(to get horizontal scrolling images)

            let imageView1 = UIImageView()
            imageView1.image = imageArray[i]
            imageView1.contentMode = .scaleAspectFit
            let xPosition = self.view.frame.width * CGFloat(i)
            imageView1.frame = CGRect(x: xPosition, y: 0, width: self.imageScrollView.frame.width, height: self.imageScrollView.frame.height)

            imageView1.addSubview(viewFN)

            imageScrollView.contentSize.width = imageScrollView.frame.width * (CGFloat(i + 1))
            imageScrollView.addSubview(imageView1)

            let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.cancelClick))
            imageView1.addGestureRecognizer(tap2)
            imageView1.isUserInteractionEnabled = true

            passedIndex = i
            print(passedIndex)
            imageView1.tag = passedIndex
        }
    } else {
        //Error here
    }        
    self.dismiss(animated: true, completion: nil)
}

3 个答案:

答案 0 :(得分:0)

imageArray.remove(at:passedIndex)它的意思是,你只从数组中删除对象的引用。如果你想从屏幕中删除对象,你需要使用 imageview.removeFromSuperview ()

答案 1 :(得分:0)

这可以像这样解决......

func cancelClick() {
    imageArray.remove(at: passedIndex)

    if let viewWithTag = self.view.viewWithTag(passedIndex) {
        viewWithTag.removeFromSuperview()
    }else{
        //Do something
    }

}

答案 2 :(得分:0)

我建议通过 tag 属性识别所需的图像视图,这是您在实施时已经执行的操作:

imageView1.tag = passedIndex

此时,你可以通过标签获取图片视图,怎么做?

假设您能够知道passedIndex值是什么,因为图片视图(imageView1)是imageScrollView中的子视图,您可以按如下方式获取:< / p>

func cancelClick() {
    imageArray.remove(at: passedIndex)

    // it should be 'imageView1':
    let desiredImageView = imageScrollView.subviews.filter { $0.tag == passedIndex }.first
    desiredImageView?.removeFromSuperview()
}