ios - 拖动 super View 时更新 UILabel 的文本

标签 ios swift autolayout uilongpressgesturerecogni

在我的应用程序中,我使用 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/

相关文章:

ios - 如果数据为空,我们如何替换/删除元素

ios - 即使从 Facebook 设置中删除应用程序后,AccessToken 仍然存在

ios - 自定义开放图谱故事未通过 Facebook 审核

ios - 在一个按钮上点击大约 60 多次我的 iPad 应用程序变慢然后最终崩溃

ios - 带有 switch 语句的 SwiftUI 动画

ios - UILabel/UITextField 不使用异步 HTTP 请求更新

xcode - dyld : Library not loaded: @rpath/libswiftContacts. 动态库

ios - 动态调整 UICollectionView 的补充 View (包含多行 UILabel 的)

ios - 空 UIView 上的自动布局约束无法按预期工作

ios - AVAsset 维度 : track's naturalSize is not the size off the exported video