簡體   English   中英

iOS / Swift:使用touchesmoved移動UIImageView

[英]iOS/Swift: Using touchesmoved to move UIImageView

Swift / iOS的新功能。 我正在嘗試在調用touchesmoved時移動UIImageView。 但是,我似乎無法正常工作。 touchesMoved不會找到與touch.view相匹配的子視圖,因此不會移動該子視圖。

視圖中有可以與touchesMoved函數一起使用的UILabel,但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")
    }
}

看起來您正在嘗試在觸摸開始的位置添加圖像視圖,但是觸摸的view屬性永遠不會改變。 也就是說,當您將手指移動到不同的視圖時, touch.view不會改變,因此touch.view永遠不會與您在touchesBegan(withEvent)添加的圖像視圖相對應。

PS:命名您的類TouchPointModel有點令人困惑,因為“模型”和“視圖”類是標准模型-視圖-控制器范例中的兩種完全不同的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM