gpt4 book ai didi

xcode - 如何使 UIImageView 可点击并使其执行某些操作? ( swift )

转载 作者:IT王子 更新时间:2023-10-29 05:45:25 24 4
gpt4 key购买 nike

(我几天前才开始使用 Swift,对编程还比较陌生,所以请耐心等待。)我正在尝试让随机 block 出现在屏幕上,用户必须点击它们才能使它们消失。我已经能够创建 block ,但我不知道如何真正使它们可点击。有人可以帮帮我吗?到目前为止,这是我的代码:

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()


})



}

最佳答案

创建 View 后,您需要将其 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:,这是识别手势时发生 Action 的地方。被识别的手势将作为参数发送,您可以从它们的手势 View 属性中找出哪个 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!
}

关于xcode - 如何使 UIImageView 可点击并使其执行某些操作? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28522104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com