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

问题描述

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...