![](/img/trans.png)
[英]How do I programatically assign a UIViews Autolayout edges to match the superview?
[英]How can I get the edges of a UIImageView to snap to the edges of the screen (superview)?
我不希望有人為我編寫代碼。 我只是想朝着正確的方向推動使用的框架和/或方法。 我想做的是,在iOS Swift中,允許用戶選擇一張照片並將其放在屏幕上。 我已經把那部分工作了。 我也可以使用它,您可以拖動圖像將其定位,然后捏捏以使其更大或更小。 但是,“棘手”部分如下...當一條邊緣(或多個邊緣)接近超級視圖(屏幕)的框架時,我希望ImageView在邊緣處“捕捉”到位。 基本上,我希望圖像的邊緣被“磁性”吸引到屏幕的邊緣。 我不確定哪種方法最適合完成此任務。 任何建議表示贊賞。
編輯:這是我到目前為止...
class AdjustableImageView: UIImageView {
var parent:ViewController!
// last location for view
var lastSavedLocation = CGPointZero
override init(frame: CGRect) {
super.init(frame: frame)
// add pan gesture to view
let panGesture = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
let longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
let pinchGesture = UIPinchGestureRecognizer(target: self, action: "pinchRecognized:")
self.addGestureRecognizer(panGesture)
self.addGestureRecognizer(longPressGesture)
self.addGestureRecognizer(pinchGesture)
self.userInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pinchRecognized(pinch: UIPinchGestureRecognizer) {
// change view scale based on pinch
self.transform = CGAffineTransformScale(self.transform, pinch.scale, pinch.scale)
pinch.scale = 1.0
}
func handlePanGesture(gesture: UIPanGestureRecognizer) {
// find translation in main view
let newTranslation = gesture.translationInView(self.superview)
// set current object to new position
self.center = CGPointMake(self.lastSavedLocation.x + newTranslation.x , self.lastSavedLocation.y + newTranslation.y)
}
// detect touch for the current view and change last save postion
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// move touched view to front.
self.superview?.bringSubviewToFront(self)
self.layer.borderColor = UIColor.greenColor().CGColor
self.layer.borderWidth = 2
// save view location
self.lastSavedLocation = self.center
parent.imageSelected(self)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.layer.borderWidth = 0
}
}
在我看來,您想要像最熱門的東西。
因此,我認為您想使用拖放功能。 命中觸發(marth)(5-10或15dp / px)時,您立即鎖定圖像=>停止拖動並以編程方式定位視圖...我沒有對此進行測試,但是trhat是我的第一種方法。
雖然您不想使用子視圖進行測試,但是要使用子視圖的邊緣進行測試,但我認為這是可能的。
鏈接上方看起來像一個平滑的邊緣裁剪。 顛倒邏輯,您應該可以將邊界剪裁為...
您可以嘗試使用一種方法來檢查UIImageView的邊緣是否在超級視圖的框架的一定距離內。
func checkEdge(view: UIImageView) {
let left = view.frame.minX
let right = view.frame.maxX
let bottom = view.frame.maxY
let top = view.frame.minY
if left <= 10 {
// Move view to left side
} else if right <= 10 {
// Move view to right side
} else if bottom <= 10 {
// Move view to bottom
} else if top <= 10 {
// Move view to top
} else {
// Do nothing
}
}
讓我知道這是否奏效和/或您正在尋找什么!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.