gpt4 book ai didi

ios - 在 Swift 中每次点击都执行一些操作

转载 作者:行者123 更新时间:2023-11-30 13:47:01 25 4
gpt4 key购买 nike

每次点击屏幕时,我都试图让一个正方形出现在 Swift 中的随机 CGPoint 上。下面是我所做的,没有编译器错误,但是一旦运行应用程序,我可以单击或拖动来移动我的“人”,但每次我这样做时,都不会出现更小的方 block 。任何建议或解决方案都很棒。谢谢你!顺便说一句,UIImageView 不是图像,但有一个可行的背景颜色。`

`

    @IBOutlet weak var person: UIImageView!

var location = CGPoint(x: 0,y: 0)

var randomPoint = CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000))

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch = touches.first

location = touch!.locationInView(self.view)

person.center = location

for _ in touches {

let mySquare: UIView = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20))

mySquare.backgroundColor = UIColor.cyanColor()

mySquare.center = randomPoint

}

}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch = touches.first

location = touch!.locationInView(self.view)

person.center = location

for _ in touches {

let mySquare: UIView = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20))

mySquare.backgroundColor = UIColor.cyanColor()

mySquare.center = randomPoint

}
}`

最佳答案

对于每次触摸,您只需要在触摸开始(或触摸结束)中创建并添加(您错过了这一步)方 block ,而不是在触摸移动中进行操作。

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch = touches.first

location = touch!.locationInView(self.view)

person.center = location

for _ in touches {

let mySquare: UIView = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20))

mySquare.backgroundColor = UIColor.cyanColor()

mySquare.center = randomPoint

view.addSubview(mySquare) // add square to the view

}

}

关于ios - 在 Swift 中每次点击都执行一些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802970/

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