如何在Swift中停止ViewController?

时间:2016-06-29 15:39:10

标签: ios swift viewcontroller

我的ViewController仍在发送数组更新,即使我在另一个视图中,我该怎么办?这是我的代码:

import UIKit
import CoreBluetooth

class ViewController: UIViewController {
var audioVibe : AudioVibes!
var superpowered:Superpowered!
var displayLink:CADisplayLink!
var layers:[CALayer]!
var magnitudeArray : [UInt16] = [0, 0, 0, 0, 0, 0, 0]


override func viewDidLoad() {
    super.viewDidLoad()

    // Setup 8 layers for frequency bars.
    let color:CGColorRef = UIColor(red: 0, green: 0.6, blue: 0.8, alpha: 1).CGColor
    layers = [CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer()]
    for n in 0...7 {
        layers[n].backgroundColor = color
        layers[n].frame = CGRectZero
        self.view.layer.addSublayer(layers[n])
    }

    superpowered = Superpowered()

    // A display link calls us on every frame (60 fps).
    displayLink = CADisplayLink(target: self, selector: #selector(ViewController.onDisplayLink))
    displayLink.frameInterval = 1
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}

// Gets triggered when you leave the ViewController.
override func viewWillDisappear(animated: Bool) {
    superpowered.togglePlayback();
    superpowered.moritz();
    //delete(superpowered);
}

func onDisplayLink() {
    // Get the frequency values.
    let magnitudes = UnsafeMutablePointer<Float>.alloc(8)
    superpowered.getMagnitudes(magnitudes)

    // Wrapping the UI changes in a CATransaction block like this prevents animation/smoothing.
    CATransaction.begin()
    CATransaction.setAnimationDuration(0)
    CATransaction.setDisableActions(true)

    // Set the dimension of every frequency bar.
    let originY:CGFloat = self.view.frame.size.height - 20
    let width:CGFloat = (self.view.frame.size.width - 47) / 5
    var frame:CGRect = CGRectMake(20, 0, width, 0)
    for n in 0...4 {
        frame.size.height = CGFloat(magnitudes[n]) * 2000
        frame.origin.y = originY - frame.size.height
        layers[n].frame = frame
        frame.origin.x += width + 1
    }

    // Set the magnitudes in the array.
    for n in 0...6 {
        magnitudeArray[n] = UInt16(magnitudes[n] * 32768)
    }

    // Update the array in the audioVibe class to trigger the sending command.
    audioVibe.magnitudeArray = magnitudeArray

    CATransaction.commit()

    // Dealloc the magnitudes.
    magnitudes.dealloc(8)
}

}

我希望他停止做audioVibe.magnitudeArray = magnitudeArray这样的事情而我不在他看来,我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:0)

在viewDidLoad方法中,您可以创建CADisplayLink并将其添加到运行循环中。

如果您没有做任何事情,当您在其上按下另一个视图控制器时,该显示链接将保持活动状态。

您应该移动创建显示链接的代码,并将其添加到viewWillAppear方法的运行循环中。

然后你需要在viewWillDisappear中添加代码,从运行循环中删除显示链接,使其无效,并将其删除。

这样,当视图出现时,您将启动显示链接代码,并在视图消失时停止显示链接代码。

答案 1 :(得分:0)

当您转换到不同的视图时,看起来您显示的链接没有暂停。

您可以在转移离开此视图时暂停显示链接,并在使用paused上的CADisplayLink属性返回此视图时恢复显示链接。您可以将其暂停在viewWillDisappear中,然后在viewWillAppear中继续。