检测关于容器视图的 UIView 中心位置 - Swift - 以编程方式

detect UIView center position in regards to container View - Swift - Programmatically

我在 ViewController 视图上添加了一个 UIView 卡片:

self.view.addSubview(cardView)
cardView.anchor(top: self.topWhiteView.bottomAnchor, leading: view.leadingAnchor, bottom: buttonsStackView.topAnchor, trailing: view.trailingAnchor, padding: .init(top: 15, left: 10, bottom: 10, right: 10))

我在上面添加了一个 panGestureRecogniser,我可以用它来拖动卡片。 平移方法:

@objc func handlePan(gesture : UIPanGestureRecognizer){
    
    
    switch gesture.state {
    case .changed:
        handleChanged(gesture)
    case .ended:
        handleEnded(gesture)
    default:
        ()
    }
    
    
}


fileprivate func handleChanged(_ gesture: UIPanGestureRecognizer) {
    
    
    let translationY = gesture.translation(in: nil).y
    var scaleValue : CGFloat = 1
    let multiplier = 1.1*translationY
    if translationY != 0 {
        scaleValue = 1 - (abs(translationY*multiplier)/abs(translationY)/3000)
    }


    let scale = CGAffineTransform(scaleX: scaleValue, y: scaleValue)

    let translation = gesture.translation(in: nil)
    let rotationRadiant: CGFloat = translation.x / 20
    let rotationDegree = (rotationRadiant * .pi) / 180
    let rotationalTransformation = CGAffineTransform(rotationAngle: rotationDegree)
    self.transform = rotationalTransformation.translatedBy(x: translation.x, y: translation.y).concatenating(scale)
    
    
   }


fileprivate func handleEnded(_ gesture: UIPanGestureRecognizer) {
    
    UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.1, options: [.curveEaseOut, .allowUserInteraction], animations: {
        
        self.transform = CGAffineTransform.identity
        
    })
}

我想知道当卡片移动时如何检测 cardView 的中心位置。

但与其他 Stack Overflow 问题不同,我想在 cardView class 中完成,而不使用任何委托。

不确定我是否完全理解您的需求,但请尝试以下操作

class CardView: UIView {
    override var center: CGPoint {
        get { super.center }
        set {
            super.center = newValue
            didMove(to: newValue)
        }
    }

    private func didMove(to point: CGPoint) {
        // do anything needed with new position
    }
}