【问题标题】:Swift: I'm super confused! UIGravityBehavior vs NSTimer vs CGPointMake on UILabel斯威夫特:我超级困惑! UILabel 上的 UIGravityBehavior vs NSTimer vs CGPointMake
【发布时间】:2015-01-02 17:00:06
【问题描述】:

所以我声明了一个 UILabel!命名为“textLabel”,它具有上升的重力效果。现在,当它达到 -30 时,我希望标签重新出现在 (200, 444) 处。我使用 NSTimer 检查是否(labelText > -30),但是当它到达/通过该点时,它只是在它应该出现的位置(在中间附近)闪烁,但它不是从中间开始。这是我的大部分代码。

如何让标签出现在它的新位置?所以一旦它在y轴上达到-30,它就可以再次循环?我已经搜索和搜索。帮顶

@IBOutlet weak var textLabel: UILabel!

var gravity: UIGravityBehavior!
var animator: UIDynamicAnimator!
var itemBehavior: UIDynamicItemBehavior!

var boundaryTimer = NSTimer()

Override func viewDidLoad() {
    animator = UIDynamicAnimator(referenceView: view)
    gravity = UIGravityBehavior(items: [textLabel])
    animator.addBehavior(gravity)

    boundaryTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "leftBoundary", userInfo: nil, repeats: true)

    itemBehavior = UIDynamicItemBehavior(items: [textLabel])
    itemBehavior.elasticity = 1.2
    gravity.gravityDirection = CGVectorMake(0.0 , -0.01)
    animator.addBehavior(itemBehavior)
}

func leftBoundary() {
    if textLabel.center.y < 40 {

        self.textLabel.center = CGPointMake(200, 444)
    }
}

【问题讨论】:

    标签: ios iphone ipad swift ios8


    【解决方案1】:

    除了设置center之外,您还可以添加然后删除附件行为,例如:

    func leftBoundary() {
        if textLabel.center.y < 40 {
            let attachment = UIAttachmentBehavior(item: textLabel, attachedToAnchor: textLabel.center)
            animator.addBehavior(attachment)
            attachment.anchorPoint = view.center
            attachment.action = {[unowned self, attachment] in
                if self.textLabel.center.y > 100 {
                    self.animator.removeBehavior(attachment)
                }
            }
        }
    }
    

    请注意,您可能需要更改 itemBehavior,使 allowRotationfalse(取决于您所需的 UI)。

    另外请注意,我在这里使用的 action 也可以用于 gravity 行为。因此,不要使用计时器(它可能不会总是同时捕获标签),而是使用 action,它会在动画的每一帧上调用。

    【讨论】:

    • Rob-这行得通!它确实出现在屏幕中间(view.center),但我如何让它出现在底部?我尝试了几件事,但无济于事。附言。我是新来的。也提前谢谢你。
    • 与其将anchorPoint 设置为view.center,不如将​​其设置为其他值(例如,使用CGPointMake)。
    【解决方案2】:

    您应该首先从动画师中删除所有标签行为。

    这与 UIKit Dynamics 的工作方式有关。它实际上只操作视图的层/表示层,因此如果您想自己设置位置,则需要重置所有内容(通过视图,这也会影响层)。

    另外,我认为定时器的设置不是很有效。相反,您应该尝试一下 KVO(键值观察)。您可以观察关键路径“center.y”并在超出限制时做出反应。

    【讨论】:

      猜你喜欢
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多