如何制作运行函数的可点击UIImages?(Swift)

时间:2015-02-15 04:54:02

标签: swift uiimageview clickable

(我刚刚开始使用Swift,并且对编程比较新,所以请耐心等待。)我试图在屏幕上显示随机块,用户必须点击它们才能使它们消失。我已经能够创建块,但我不知道如何实际使它们可以应用。有人可以帮帮我吗?到目前为止,这是我的代码:

func createBlock(){

    let imageName = "block.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)

    imageView.frame = CGRect(x: xPosition, y: -50, width: size, height: size)
    self.view.addSubview(imageView)

    UIView.animateWithDuration(duration, delay: delay, options: options, animations: {

        imageView.backgroundColor = UIColor.redColor()
        imageView.frame = CGRect(x: self.xPosition, y: 590, width: self.size, height: self.size)

        }, completion: { animationFinished in


            imageView.removeFromSuperview()
            self.life-=1


    })



}

我想在敲击时让块消失;关于如何做到这一点的任何建议?

2 个答案:

答案 0 :(得分:0)

这非常简单,只需使用UITapGestureRecognizer即可。我通常将识别器初始化为全局变量。

let tapRecognizer = UITapGestureRecognizer()

然后在你的viewDidLoad:

// Replace with your function
tapRecognizer.addTarget(self, action: "removeBlock")
imageView.addGestureRecognizer(tapRecognizer)

答案 1 :(得分:0)

func removeImage(gesture: UIGestureRecognizer) {
    gesture.view?.removeFromSuperview()
}

func createBlock() {
    let imageName = "block.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)

    imageView.frame = CGRect(x: xPosition, y: -50, width: size, height: size)

    imageView.userInteractionEnabled = true                       // IMPORTANT
    imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "removeImage:"))

    self.view.addSubview(imageView)

    UIView.animateWithDuration(duration, delay: delay, options: options, animations: {

        imageView.backgroundColor = UIColor.redColor()
        imageView.frame = CGRect(x: self.xPosition, y: 590, width: self.size, height: self.size)

    }, { _ in
        imageView.removeFromSuperview()
        self.life-=1
    })
}

注意imageView.userInteractionEnabled = true这非常重要,因为这将允许该视图上的触摸事件,在UIImgageView中将其设置为false作为默认值。