swift - 如何保持不断变化的视图居中?
问题描述
我正在创建一个 UIView,它基本上是一个带边框的透明 UIView。
此视图正在使用此代码进行动画处理
UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: {
var frame = areaScanRect.frame
frame.size.width = frame.size.width * 0.8
frame.size.height = frame.size.height * 1.2
areaScanRect.frame = frame
}, completion: nil)
该视图的框架类似于 (0,0,200,100)。
我需要这个视图以主视图为中心。
如果我只是将矩形添加到主视图中,它会出现在 (0,0) 处,而不是显然在屏幕中心。
然后我添加约束,使其居中。
areaScanRect.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
areaScanRect.centerXAnchor.constraint(equalTo: view.centerXAnchor),
areaScanRect.centerYAnchor.constraint(equalTo: view.centerYAnchor),
areaScanRect.widthAnchor.constraint(equalToConstant: areaScanRect.bounds.size.width),
areaScanRect.heightAnchor.constraint(equalToConstant: areaScanRect.bounds.size.height)
])
areaScanRect
显示在正确的位置,但随着动画的进行,没有居中。
为什么?
解决方案
可能这个代码会起作用:'''
func setMyView(_point: CGPoint) {
var newView = CGPoint(x: bounds.size.width * point.x, y: bounds.size.height * point.y)
var oldView = CGPoint(x: bounds.size.width * layer.anchorPoint.x, y: bounds.size.height * layer.anchorPoint.y);
newView = newView.applying(transform)
oldView = oldView.applying(transform)
var position = layer.position
position.x -= oldView.x
position.x += newView.x
position.y -= oldView.y
position.y += newView.y
layer.position = position
layer.anchorView = point
}
}
推荐阅读
- android - MpChartlibrary 背景颜色变化
- php - PHP 和 Carbon:如何获得不同年份的相对时间
- python - 格式化日期时间熊猫
- python-3.x - Django Channels:从通道层发送的数据包未传递
- c# - 数据表编辑器 - Field.Options.Where 语法
- ruby-on-rails - 是否可以通过自定义 UI 和 Angular/React 等前端框架单独使用 ActiveAdmin API 端点?
- android - Android Drive API 读写文件
- php - 我的codeigniter查询正确吗?
- google-maps-api-3 - 位于任何谷歌 api 上的信息是否可用?
- javascript - How can you do WebRTC over a local network with no internet connection?