swift - viewDidLoad 中设置的变量稍后变为 nil

标签 swift

我遇到了一个奇怪的问题,我在 viewDidLoad 中设置了其中一个变量后将其设置为 nil。

我正在使用 videoPreviewLayer AVPreview,并且有很多不同的 session 队列在进行,所以我可能没有正确理解某些内容。 我可以使用帮助来诊断问题。 代码很长,但很简单。如果有任何帮助,我们将不胜感激。完整代码在这里:https://gist.github.com/makthrow/0570cc571f1c7866e094096626c19498

和简短的版本:

var customRecordButton : RecordButton!
var progressTimer : Timer!
var progress : CGFloat! = 0



override func viewDidLoad() {
    super.viewDidLoad()



    // custom recordButton https://github.com/samuelbeek/recordbutton
    let recordButtonRect = CGRect(x: 0, y: 0, width: 70, height: 70)
    let customRecordButton = RecordButton(frame: recordButtonRect)
    customRecordButton.center = self.view.center
    customRecordButton.progressColor = UIColor.red
    customRecordButton.closeWhenFinished = false
    customRecordButton.center.x = self.view.center.x
    customRecordButton.addTarget(self, action: #selector(self.record), for: .touchDown)
    customRecordButton.addTarget(self, action: #selector(self.stop), for: UIControlEvents.touchUpInside)
    self.view.addSubview(customRecordButton)
    }
func record() {
    self.progressTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true)
}

func updateProgress() {


    let maxDuration = CGFloat(5) // max duration of the recordButton

    progress = progress + (CGFloat(0.05) / maxDuration)
    customRecordButton.setProgress(progress) // (customRecordButton is always nil here)

    if progress >= 1 {
        progressTimer.invalidate()
    }

}

基本上,在 updateProgress() 中,customRecordButton 始终为 nil

我尝试浏览代码,在 viewWillAppear 中,customRecordButton 也为 nil。我不确定我在这里使用的 RecordButton 类是否有问题:https://github.com/samuelbeek/RecordButton 我不认为应该有问题..

编辑 1:在 viewDidLoad 之上添加了变量。我把它们放在那里只是忘了粘贴它们。

编辑 2:顺便说一句,录制按钮显示在我的手机用户界面上,当我按下它时它告诉我 customRecordButton 为 nil

最佳答案

var customRecordButton: RecordButton?

override func viewDidLoad() {
    super.viewDidLoad()

    // custom recordButton https://github.com/samuelbeek/recordbutton
    let recordButtonRect = CGRect(x: 0, y: 0, width: 70, height: 70)
    customRecordButton = RecordButton(frame: recordButtonRect)

...

customRecordButton?.setProgress(progress)

关于swift - viewDidLoad 中设置的变量稍后变为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39713052/

相关文章:

ios - Swift - 如何 shouldOverrideUrlLoading

ios - 从今天的日期减去周和天时的剩余小时

ios - 快速动画不工作

swift - Swift 中未通过委托(delegate)调用函数

swift - 在 Swift 中创建一个包含多个数组的数组

swift - ASPasswordCredential - 来自哪里?

ios - JSON 未在 TableView 中加载

ios - 使用 OHHTTPStubs 进行模拟时未到达 Alamofire 响应 block

ios - 从 TabBarController 的 subview 在 TabBar 后面插入 subview

ios - 子类化与协议(protocol)