xcode – 如何使UIImageView可以兼容并使其执行某些操作? (迅速
发布时间:2020-12-15 01:50:44 所属栏目:百科 来源:网络整理
导读:(我刚开始使用Swift几天前对编程比较新,所以请耐心等待.)我试图在屏幕上显示随机块,用户必须点击它们才能使它们消失.我已经能够创建块,但我不知道如何实际使它们可以应用.有人可以帮帮我吗?到目前为止这是我的代码: func createBlock(){ let imageName = "
(我刚开始使用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,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,animations: { imageView.backgroundColor = UIColor.redColor() imageView.frame = CGRect(x: self.xPosition,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:,这是识别手势时动作发生的地方.已识别的手势将作为参数发送,您可以从手势视图属性中找出从哪个图像视图中点击. func imageTapped(gestureRecognizer: UITapGestureRecognizer) { //tappedImageView will be the image view that was tapped. //dismiss it,animate it off screen,whatever. let tappedImageView = gestureRecognizer.view! } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |