快速平移手势移动约束

Posted

技术标签:

【中文标题】快速平移手势移动约束【英文标题】:Swift pan gesture movement constraints 【发布时间】:2015-09-19 18:15:35 【问题描述】:

我试图阻止我的 UILabel 向下移动到 CONTROLTOPOFFSET 以下。

CONTROLTOPOFFSET = (UIScreen.mainScreen().bounds.size.height - CONTROLSIZE) - CONTROLPAD

我正在使用UIPanGestureRecognizer 并想在此函数中运行检查,只是不确定如何。

func moveScore(gesture: UIPanGestureRecognizer) 

    let tranlation: CGPoint = gesture.translationInView(boardView)
        gesture.view?.center = CGPointMake(gesture.view!.center.x +   tranlation.x, gesture.view!.center.y + tranlation.y)


    gesture.setTranslation(CGPointMake(0, 0), inView: boardView) 

【问题讨论】:

【参考方案1】:

如果不了解您的视图层次结构,很难回答这个问题。假设您的视图层次结构只是来自视图控制器的视图,其中板视图作为子视图,其标签作为子视图,

<UIWindow: 0x7fdf5c8157e0; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x7fdf5c816ba0>; layer = <UIWindowLayer: 0x7fdf5c814950>>
   | <UIView: 0x7fdf5c91ec40; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x7fdf5c91eda0>>
   |    | <UIView: 0x7fdf5ad11380; frame = (107 268; 200 200); autoresize = RM+BM; layer = <CALayer: 0x7fdf5ad10aa0>>
   |    | <UILabel: 0x7fdf5c91c280; frame = (209 464.333; 42 21); text = 'Label'; opaque = NO; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7fdf5c922850>; layer = <_UILabelLayer: 0x7fdf5c91c670>>

你可以这样做:

import UIKit

class ViewController: UIViewController 

  @IBOutlet weak var label: UILabel!
  @IBOutlet weak var boardView: UIView!

  var CONTROLTOPOFFSET : CGFloat 
    get 
      let CONTROLSIZE : CGFloat = 200.0
      let CONTROLPAD : CGFloat = 10.0
      return (UIScreen.mainScreen().bounds.size.height - CONTROLSIZE) - CONTROLPAD
    
  

  override func viewDidLoad() 
    super.viewDidLoad()
    let panGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: "moveScore:")
    label.userInteractionEnabled = true
    label.addGestureRecognizer(panGestureRecognizer)
  

  func moveScore(gesture: UIPanGestureRecognizer) 

    let tranlation: CGPoint = gesture.translationInView(view)
    let newPosition = CGPointMake(gesture.view!.center.x + tranlation.x, gesture.view!.center.y + tranlation.y)
    if newPosition.y < CONTROLTOPOFFSET 
      gesture.view?.center = newPosition
      gesture.setTranslation(CGPointMake(0, 0), inView: view)
    

  


不同之处在于翻译是针对用于您的CONTROLTOPOFFSET 的超级视图完成的,并且有一个 if 语句来防止进一步移动超出范围。

我确信您的视图层次结构比示例中的要复杂得多,但希望您可以将示例外推到您的代码中。

【讨论】:

以上是关于快速平移手势移动约束的主要内容,如果未能解决你的问题,请参考以下文章

收缩高度约束动画问题

约束 UIScrollView 平移?

Swift:使用约束平移 UIImage

动态调整视图大小(拖动运动)时自动布局约束中断

将平移手势传递给 MKMapView

Stackview内的布局约束(以编程方式快速移动)