每次点击屏幕时,我都试图在Swift中的随机CGPoint上出现一个正方形。下面是我没有编译错误的事情,但是一旦我运行应用程序,我可以点击或拖动来移动我的人,"但每次我这样做,都不会出现较小的正方形。任何建议或解决方案都很棒。谢谢!顺便说一句,人,UIImageView是没有图像,但有一个可行的backgroundColor。
`
@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
}
}`
答案 0 :(得分:0)
您没有将mySquare
视图添加到任何视图中。
self.view.addSubview(mySquare)
答案 1 :(得分:0)
对于每次触摸,你只需要创建并添加(你错过了这一步)方形触摸开始(或触摸结束),不要触摸移动。
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
}
}