(我几天前刚开始使用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
})
}
我想让方块在敲击时消失;关于我该怎么做有什么建议吗?
这非常简单,只需使用UIMapGestureRecognizer即可。我通常将识别器初始化为全局变量。
let tapRecognizer = UITapGestureRecognizer()
然后在您的视图中DidLoad:
// Replace with your function
tapRecognizer.addTarget(self, action: "removeBlock")
imageView.addGestureRecognizer(tapRecognizer)
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作为defaul。