【问题标题】:Do something every click in Swift在 Swift 中每次点击都做一些事情
【发布时间】:2016-01-15 01:36:13
【问题描述】:

每次单击屏幕时,我都会尝试在 Swift 中的随机 CGPoint 上显示一个正方形。下面是我在没有编译器错误的情况下所做的,但是一旦我运行应用程序,我可以单击或拖动来移动我的“人”,但每次我这样做时,都不会出现一个较小的正方形。任何建议或解决方案都很棒。谢谢!顺便说一句,人,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

        }
    }`

【问题讨论】:

    标签: ios swift click uitouch


    【解决方案1】:

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

        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
    
            }
    
        }
    

    【讨论】:

      【解决方案2】:

      您没有将mySquare 视图添加到任何视图中。

       self.view.addSubview(mySquare)
      

      【讨论】:

      • 请多解释一下你的代码。这个答案对于新手来说太短了
      • 代码很明显表明需要在父视图上添加。为什么要投反对票?看不懂就不要在这里问了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2018-11-12
      • 2018-06-18
      • 2019-04-01
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多