我正在学习 Matt Neuburg 的书 ios 13 Dive deep into views 并偶然发现了示例“dragByAttachment”。这里:
@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
}
}
这条线让我很困惑:
let att = UIAttachmentBehavior(item:p.view!,
offsetFromCenter:UIOffset(horizontal: loc.x - cen.x , vertical:loc.y - cen.y))
因为只有在 offsetFromCenter 等于 UIOffset(horizontal: loc.x - cen.x , vertical:loc.y - cen.y) 的情况下,该属性(offsetFromCenter) 并没有按照苹果文档所说的关于 offsetFromCenter 的工作。我附上了 gif 结果:
视图(黑盒)中心点没有偏移。我们从什么时候开始进行实验并不重要。
但是如果我们将 offsetFromCenter 属性从之前的 UIOffset(horizontal: loc.x - cen.x , vertical:loc.y - cen.y) 更改为 new UIOffset(horizontal: loc.x - cen.x - 20 , vertical:loc .y - cen.y - 20) 这个修改后的属性会根据 Apple 的文档对 UIAttachmentBehavior 进行调整。我附上了gif
为什么在第一个例子中它表现得那么奇怪?