Strange behavior of the "offsetFromCenter" property of UIAttachmentBehavior

55 views Asked by At

I was learning Matt Neuburg's book ios 13 Dive deep into views and stumbled upon example "dragByAttachment". Here:

 @IBAction func dragging(_ p: UIPanGestureRecognizer) {
    switch p.state {
    case .began:
        self.anim = UIDynamicAnimator(referenceView:self.view)
        self.anim.perform(Selector(("setDebugEnabled:")), with:true)
        self.anim.delegate = self
        let loc = p.location(ofTouch:0, in:p.view)
        let cen = p.view!.bounds.center
    
        
        let anchor = p.location(ofTouch:0, in:self.view)
        let att = UIAttachmentBehavior(item:p.view!,
                                       offsetFromCenter:UIOffset(horizontal: loc.x - cen.x  , vertical:loc.y - cen.y), attachedToAnchor:anchor)
        self.anim.addBehavior(att)
        let b = UIFieldBehavior.linearGravityField(direction:CGVector(0,1))
        b.addItem(p.view!)
        b.strength = 0.4
        b.direction = CGVector(dx: 0, dy: 1)
   
        self.anim.addBehavior(b)
        self.att = att
    case .changed:
       // print()
        self.att.anchorPoint = p.location(ofTouch:0, in: self.view)
    default:
        print("done")
        self.anim = nil
    }
}

This line confused me a lot:

 let att = UIAttachmentBehavior(item:p.view!,
                                       offsetFromCenter:UIOffset(horizontal: loc.x - cen.x  , vertical:loc.y - cen.y))

because only in case of offsetFromCenter was equal to UIOffset(horizontal: loc.x - cen.x , vertical:loc.y - cen.y),that property(offsetFromCenter) was not doing what apple doc was saying us about offsetFromCenter job. Here gif result i attached: enter image description here

There is no offset from views(black box) center point. And it doesn't matter from what point we would conducting the experiment.

but if we change the offsetFromCenter property from previous UIOffset(horizontal: loc.x - cen.x , vertical:loc.y - cen.y) to new UIOffset(horizontal: loc.x - cen.x - 20 , vertical:loc.y - cen.y - 20) this modified property makes adjustments to UIAttachmentBehavior according to Apple's documentation as it should. i attached gif enter image description here

Why in the first example it behaves that strange way?

0

There are 0 answers