(几天前我才刚开始使用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() }) }
编辑: 这是我正在尝试的新代码:
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) imageView.userInteractionEnabled = true let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped")) imageView.addGestureRecognizer(tapRecognizer) func imageTapped(gestureRecognizer: UITapGestureRecognizer) { let tappedImageView = gestureRecognizer.view! tappedImageView.removeFromSuperview() score += 10 } 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() }) }
创建视图后,需要将其userInteractionEnabled属性设置为true。然后,您需要向其附加手势。
imageView.userInteractionEnabled = true //now you need a tap gesture recognizer //note that target and action point to what happens when the action is recognized. let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped:")) //Add the recognizer to your view. imageView.addGestureRecognizer(tapRecognizer)
现在您仍然需要该函数,在本例中为imageTapped:,这是识别手势后动作发生的位置。识别出的手势将作为参数发送,您可以从他们的手势视图属性中找出点击了哪个imageView。
func imageTapped(gestureRecognizer: UITapGestureRecognizer) { //tappedImageView will be the image view that was tapped. //dismiss it, animate it off screen, whatever. let tappedImageView = gestureRecognizer.view! }