iOS / Swift:使用touchesmoved移动UIImageView

时间:2015-11-16 16:14:24

标签: ios swift uiimageview

Swift / iOS新手。我正在尝试在调用touchesmoved时移动UIImageView。但是,我似乎无法让它发挥作用。 touchesMoved将找不到与touch.view匹配的子视图,因此不会移动子视图。

视图中有UILabel可以使用touchesMoved函数,但UIImageViews不会。

任何想法都会非常有用。感谢。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch = touches.first as UITouch!
    let location = touch.locationInView(view)

    let imageView = TouchPointModel(frame: CGRectMake(location.x - frameSize * 0.5, location.y - frameSize * 0.5, frameSize, frameSize), image: UIImage(named: "Feedback_Winner.png")!)

    view.addSubview(imageView)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch:AnyObject in touches {
        let location = touch.locationInView(view)

        for subview in view.subviews {
            if touch.view == subview {
                print("yahtzee")
                subview.center = location
            }
        }
    }
}

以下是TouchPointModel供参考:

class TouchPointModel: UIImageView {
    init(frame:CGRect, image:UIImage) {
        super.init(frame: frame)
        self.image = image
        self.opaque = false
        self.userInteractionEnabled = true

        UIView.animateWithDuration(1.0, delay: 0.0, options: [.Repeat, .Autoreverse], animations: {
            self.transform = CGAffineTransformMakeScale(1.3, 1.3)
        }, completion: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

1 个答案:

答案 0 :(得分:1)

看起来您尝试在触摸开始时添加图像视图,但触摸的view属性永远不会改变。也就是说,当您将手指移动到不同的视图时,touch.view不会发生变化,因此touch.view将永远不会与您在touchesBegan(withEvent)中添加的图片视图相对应。

PS:命名类TouchPointModel会让人感到有点困惑,因为“模型”和“视图”类是标准模型 - 视图 - 控制器范例中两种完全不同的对象。