如何从索引中删除UIImageView?

时间:2014-10-08 06:39:23

标签: ios swift

我正在开发一个益智游戏,我将所有图像视图添加到NSMutableArray但我想删除它的第一个数组,它位于索引0我的代码是:

override func viewDidLoad() {
    super.viewDidLoad()

    var allImageViews : NSMutableArray = NSMutableArray()

    var xCen :CGFloat  = 53
    var yCen :CGFloat = 94

    for v in 0...2{

        for h in 0...2{

            let filename = String(format: "kat_%02i.gif", h+v*3)
            let Image = UIImage(named: filename)
            let myImageView = UIImageView(image: Image)
            myImageView.frame = CGRectMake(0, 0, 106, 189)
            myImageView.center = CGPointMake(xCen, yCen)
            myImageView.userInteractionEnabled = true
            allImageViews.addObject(myImageView)
            self.view.addSubview(myImageView)
            xCen += 106
        }
        xCen = 53
        yCen += 189
    }
    allImageViews.removeObjectAtIndex(0)

}

我想我会从Index中删除对象,但是当我运行项目时它仍会出现,所以任何人都可以告诉我如何从superview中删除第一张图像?

1 个答案:

答案 0 :(得分:1)

在从视图中删除之前,只需在视图上调用removeFromSuperview

allImageViews[0].removeFromSuperview()
allImageViews.removeObjectAtIndex(0)

如果您使用Swift数组而不是NSMutableArray,那么您将获得更多类型 安全,您可以利用removeAtIndex()返回的事实 删除的元素:

override func viewDidLoad() {
    super.viewDidLoad()

    var allImageViews : [UIImageView] = []

    var xCen :CGFloat  = 53
    var yCen :CGFloat = 94

    for v in 0...2{

        for h in 0...2{

            let filename = String(format: "kat_%02i.gif", h+v*3)
            let Image = UIImage(named: filename)
            let myImageView = UIImageView(image: Image)
            myImageView.frame = CGRectMake(0, 0, 106, 189)
            myImageView.center = CGPointMake(xCen, yCen)
            myImageView.userInteractionEnabled = true
            allImageViews.append(myImageView)
            self.view.addSubview(myImageView)
            xCen += 106
        }
        xCen = 53
        yCen += 189
    }

    allImageViews.removeAtIndex(0).removeFromSuperview()
}