2017-03-16 49 views
2

我在视图控制器中有一个标签。每次点击标签时,我都会将标签的位置移动到左侧。这是我迄今为止的,但我的标签不会在模拟中移动。我对标签有限制。大约100宽50高,它也集中在视图控制器中。用手势快速移动标签位置

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let tapGesture = UITapGestureRecognizer(target: gestureLabel, action: #selector(moveLabel)) 
    gestureLabel.addGestureRecognizer(tapGesture) 

} 

func moveLabel(){ 
    if(left){ 
     moveLeft() 
    } 
    else{ 
     moveRight() 
    } 

} 

func moveLeft(){ 
    let originalX = gestureLabel.frame.origin.x 
    if(originalX < 0){ 
     bringIntoFrame() 
    } 
    else{ 
     gestureLabel.frame.offsetBy(dx: -50, dy: 0) 
    } 
} 
+0

您需要更改约束的“常量”属性,而不是帧。 – Paulw11

+0

除了Paulw11的评论,你需要为水平约束创建一个属性,所以你可以这样做:'horizo​​ntal.constant - = 50; view.layoutIfNeeded()'。 – Eendje

+0

使用CGAffileTransform和translate来代替移动中心或更改偏移量。它会更容易。不需要额外的代码。 并且还设置:gestureLabel.userInteractionEnabled = true – Dari

回答

0

UILabel的userInteractionEnabledfalse默认。尝试将其设置为true

0

您应该更改标签的约束条件,而不是标签本身。

此外,您的target应该是self,而不是gestureLabel

另外,你可以动画。 :)

像这样:

class ViewController: UIViewController { 

    // Centers the Meme horizontally. 
    @IBOutlet weak var centerHorizontalConstraint: NSLayoutConstraint! 

    // A custom UIView. 
    @IBOutlet weak var okayMeme: OkayMeme! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     addGestureRecognizer() 
    } 

    func addGestureRecognizer() { 
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(moveMeme)) 
     okayMeme.addGestureRecognizer(tapGesture) 
    } 

    func moveMeme() { 
     UIView.animate(withDuration: 2.0) { 
      self.centerHorizontalConstraint.constant -= 50 
      self.view.layoutIfNeeded() 
     } 
    } 
} 

“演示”:

DEMO

0

在这里您可以将标签在任何你想要的

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
     if let touch = touches.first { 
      let position = touch.location(in: self.view) 
      print(position.x) 
      print(position.y) 
      lbl.frame.origin = CGPoint(x:position.x-60,y:position.y-50) 
     } 
    } 
0

标签不会动因为它有限制。要做到这一点最简单的方法是下一个:

1)编程方式创建一个标签(这样你就可以自由地移动它)

var labelDinamic = UILabel(frame: CGRectMake(0, 0,200, 200)); 
    labelDinamic.text = "test text"; 
    self.view.addSubview(labelDinamic); 

2)设置的标签初始位置(我建议使用的位置您有限制。同时当前标签,隐藏你约束的标签,因为你不需要来显示它)

labelDinamic.frame.origin.x = yourLabelWithConstraints.frame.origin.x; 
labelDinamic.frame.origin.y = yourLabelWithConstraints.frame.origin.y; 

3)现在你移动你的标签在任何你想用财产

labelDinamic.frame.origin.x = 123 
labelDinamic.frame.origin.y = 200 
0

您做了一个新的框架,但没有将其分配给标签。 offsetBy不会改变框架。它创造了一个新的。

更换

gestureLabel.frame.offsetBy(dx: -50, dy: 0) 

gestureLabel.frame = gestureLabel.frame.offsetBy(dx: -50, dy: 0) 

但上述方法假定,您使用的是直接,没有限制。一个标准的方法是有一个“引领超级观点”的约束,并改变其常数而不是改变框架。