拖动超级视图时更新UILabel的文本

时间:2018-01-29 22:23:17

标签: ios swift autolayout uilongpressgesturerecogni

在我的应用程序中,我使用UILongPressGestureRecognizer在屏幕上拖动视图。此视图包含一些子视图,包括UILabel,这些子视图使用约束进行布局。当我开始拖动时,我确保从拖动视图中删除所有定位约束(我保持宽度和高度约束),因为我在手势识别器更改时手动更新帧。这很好用,但是当我在拖动时更新子视图标签的文本时,被拖动的视图会在一瞬间跳转到(0,0),但是在我拖动一些其他更新到框架后再返回到正确的位置

当使用.changed状态调用手势识别器时,将运行以下代码:

let location = gesture.location(in: calendar.view)
moveView(with: location)

这完全没问题,视线跟在手指后面并没有跳过。

现在我想添加一个随位置变化而更新的标签:

let location = gesture.location(in: calendar.view)
moveView(with: location)

movingView.label.text = "Some Text: \(location.x ?? "Error")"

现在视图一直跳到(0,0)。

我试图通过使用旧框架来解决此问题,然后在我更新文本之后设置它:

let location = gesture.location(in: calendar.view)
moveView(with: location)

let oldFrame = movingView.frame
movingView.label.text = "Some Text: \(location.x ?? "Error")"
//movingView.layoutIfNeeded() -> tried with this too, to no effect
movingView.frame = oldFrame

但是,视图仍会跳转到(0,0)。所以我的问题是,可以做些什么呢?如何设置UILabel的文本而不会弄乱拖动视图?

1 个答案:

答案 0 :(得分:2)

保持视图包含所有约束,并在transform更改时使用gestureRecognizer.location移动视图:

label.transform = CGAffineTransform.identity.translatedBy(x: location.x, y: location.y)