首页 > 解决方案 > 如何保持不断变化的视图居中?

问题描述

我正在创建一个 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显示在正确的位置,但随着动画的进行,没有居中。

为什么?

标签: swiftuiviewswift5

解决方案


可能这个代码会起作用:'''

    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

     }

    }

推荐阅读