我有以下代碼將圖像拖放到另一圖像上。在橫向拖放圖像不起作用
import Foundation
import UIKit
class DragImg: UIImageView {
var originalPosition: CGPoint!
var dropTarget: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
originalPosition = self.center
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let position = touch.locationInView(self.superview)
self.center = CGPointMake(position.x, position.y)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first, let target = dropTarget {
let position = touch.locationInView(self.superview)
if CGRectContainsPoint(target.frame, position) {
let notif = NSNotification(name: "onTargetDropped", object: nil)
NSNotificationCenter.defaultCenter().postNotification(notif)
}
}
self.center = originalPosition
}
}
在肖像模式下,該效果很好,但如果我改變爲橫向模式,並嘗試拖放圖像,系統不識別圖像爲在目標圖像。你能解釋我爲什麼並指出可能的解決方案嗎?
在橫向模式下沒有touchesMoved電話? –
是的。但是問題出在touchesEnded上,因爲下面的條件不會返回true: 如果CGRectContainsPoint(target.frame,position){notllif = NSNotification(name:「onTargetDropped」,object:nil) NSNotificationCenter.defaultCenter() .post通知(notif) } 我已打印目標幀和位置,結果爲: 位置:(-254.0,169.5) 目標幀:(122.0,44.0,423.0,277.0)。 –
'self'和'target'有相同的'superview'嗎? –