【问题标题】:How to keep a changing view centered?如何保持不断变化的视图居中?
【发布时间】:2020-12-24 11:37:14
【问题描述】:

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

为什么?

【问题讨论】:

    标签: swift uiview swift5


    【解决方案1】:

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

        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
    
         }
    
        }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      myView.center.x = view.center.x
      myView.center.y = view.center.y
      

      它将使您的视图居中。

      但是我建议只将视图放置在设置其 Y 和 X 坐标的视图中,而不是使用约束

      【讨论】:

      • 不适合我。视图未居中,抱歉。
      • 尝试不受限制
      猜你喜欢
      • 2019-03-16
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2014-01-02
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多