XCode / Swift:如何管理两个重叠图像视图的约束

时间:2015-11-19 15:29:59

标签: ios xcode uiimageview constraints draggable

在我的应用程序中,我想在更大的UIImageView上管理一个可拖动的引脚,它是一个UIImageView。这是我的故事板中的截图:

enter image description here

问题是我无法管理约束:我希望pin图像只能在下面的大UIImageView中拖动。 您对如何编写这些约束有什么想法吗?

1 个答案:

答案 0 :(得分:0)

更新:回答

Main.storyboard中不需要约束,总体而言,有必要将每个引脚实现为UIImageView的子类UIPanGestureRecognizer。这是我编码允许引脚移动的尺寸的类:

import UIKit

class PinImageView: UIImageView {

var lastLocation:CGPoint?
var panRecognizer:UIPanGestureRecognizer?

init(imageIcon: UIImage?, location:CGPoint) {
    super.init(image: imageIcon)
    self.lastLocation = location
    self.panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:")
    self.center = location
    self.gestureRecognizers = [panRecognizer!]
    self.frame = CGRect(x: location.x, y: location.y, width: 20.0, height: 30.0)
    self.userInteractionEnabled = true
}

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

func detectPan(recognizer:UIPanGestureRecognizer) {
    let translation  = recognizer.translationInView(self.superview!)
    let newLocation = CGPointMake(lastLocation!.x + translation.x, lastLocation!.y + translation.y)

    if ((newLocation.x >= 26 && newLocation.x <= 292) && (newLocation.y >= 71 && newLocation.y <= 461)){
        self.center = CGPointMake(newLocation.x, newLocation.y)
    }
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // Promote the touched view
    self.superview?.bringSubviewToFront(self)

    // Remember original location
    lastLocation = self.center
}

}