gpt4 book ai didi

ios - fatal error : unexpectedly found nil while unwrapping an Optional value when defining Colors for a CAGradientLayer

转载 作者:行者123 更新时间:2023-11-30 13:33:36 24 4
gpt4 key购买 nike

我收到此错误 fatal error :

unexpectedly found nil while unwrapping an Optional value.

在此代码中

class ShimmerView: NSObject {

// weak propeties
weak var animatedView : UIView!

// Strong Properties
var shadowBackgroundColor : UIColor!
var shadowForegroundColor : UIColor!
var shadowWidth : CGFloat!
var repeatCount : CGFloat!
var duration : NSTimeInterval!

var currentAnimation : CABasicAnimation!

func commonInit(){
self.shadowBackgroundColor = UIColor(white: 1, alpha: 0.3)
self.shadowForegroundColor = UIColor.whiteColor()

self.shadowWidth = 20
self.repeatCount = CGFloat.infinity
self.duration = 3.0
}

func start(){

if(self.animatedView == nil){
print("ShimmerView has nothing to return")
self.stop()
}

let gradientMask = CAGradientLayer()
gradientMask.frame = self.animatedView.bounds

let gradientSize : CGFloat = self.shadowWidth / self.animatedView.frame.size.width

let startLocations : NSArray = [0,Int(gradientSize / 2.1),Int(gradientSize)]
let endLocations : NSArray = [Int(1.0 - gradientSize) , Int(1.0 - (gradientSize / 2.0)) , 0]
// The error is on this line
gradientMask.colors = [self.shadowBackgroundColor.CGColor , self.shadowForegroundColor.CGColor , self.shadowBackgroundColor.CGColor]
gradientMask.locations = startLocations as? [NSNumber]
gradientMask.startPoint = CGPointMake(0 - (gradientSize * 2), 0.5)
gradientMask.endPoint = CGPointMake(1 + gradientSize, 0.5)

self.animatedView.layer.mask = gradientMask

currentAnimation = CABasicAnimation(keyPath: "locations")
currentAnimation.fromValue = startLocations
currentAnimation.toValue = endLocations
currentAnimation.repeatCount = Float(self.repeatCount)
currentAnimation.duration = self.duration
currentAnimation.delegate = self

gradientMask.addAnimation(currentAnimation, forKey: "ShimmerView")
}

我已经调试过,但实际上找不到与我在发生错误的代码中编写的错误相关的任何内容

最佳答案

您将许多变量声明为隐式解包选项(在变量类型后使用 !),例如:

weak var animatedView : UIView!

来自Apple's documentation当首次定义可选值后立即确认该可选值存在并且可以肯定地假定此后的每个点都存在时,隐式解包可选值非常有用。Swift 中隐式解包可选值的主要用途是在类初始化期间"

从你的代码中我看不到正在初始化的 animatedView 变量,如果你的变量(未声明为可选变量)未初始化,则 swift 会抛出错误;但是,隐式解包选项的情况并非如此,因为它们被假定为在类初始化后立即可用。

我相信您的问题可能与此有关,您可以在引发错误的行之前设置一个断点,并找出哪个选项为零。我发现animatedView是一个弱变量,这有什么充分的理由吗?您的观点可能会在某个时候被处理。

干杯。

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value when defining Colors for a CAGradientLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com