在我的应用程序中,我使用 UILongPressGestureRecognizer
在屏幕上拖动 View 。此 View 有一些 subview ,包括使用约束进行布局的 UILabel
。当我开始拖动时,我确保从拖动的 View 中删除所有定位约束(我保留宽度和高度约束),因为我随着手势识别器的变化手动更新框架。这很好用,但是当我在拖动时更新 subview 标签的文本时,被拖动的 View 瞬间跳转到 (0,0),但在我拖动更多后返回到正确位置,这会调用另一个框架更新.
当使用 .changed
状态调用手势识别器时,将运行以下代码:
let location = gesture.location(in: calendar.view)
moveView(with: location)
这工作得很好, View 跟随手指而不会跳来跳去。
现在我想添加一个随着位置变化而更新的标签:
let location = gesture.location(in: calendar.view)
moveView(with: location)
movingView.label.text = "Some Text: \(location.x ?? "Error")"
现在 View 一直跳到 (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
然而, View 仍然跳转到 (0,0)。所以我的问题是,对此可以做些什么?如何设置 UILabel
的文本而不打乱 View 的拖动?
最佳答案
保持所有约束的 View 不变,并在 gestureRecognizer.location
更改时使用 transform
移动 View :
label.transform = CGAffineTransform.identity.translatedBy(x: location.x, y: location.y)
关于ios - 拖动 super View 时更新 UILabel 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511005/