Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 渐变变成黑色_Ios_Objective C_Swift_Uiview - Fatal编程技术网

Ios 渐变变成黑色

Ios 渐变变成黑色,ios,objective-c,swift,uiview,Ios,Objective C,Swift,Uiview,我在UIView的子视图中使用渐变,从一些应用程序切换回到应用程序后,渐变变为黑色。不知道为什么,如果有人知道这件事,请帮帮我 另外,我没有以编程的方式将其子类化,而是直接将其放在情节提要本身(CustomGradientBlueView)中UIView的类位置。这可能是个问题。? 这是我用于渐变的代码-> import UIKit class CustomGradientBlueView: UIView { required init(coder aDecoder: NSCoder

我在UIView的子视图中使用渐变,从一些应用程序切换回到应用程序后,渐变变为黑色。不知道为什么,如果有人知道这件事,请帮帮我

另外,我没有以编程的方式将其子类化,而是直接将其放在情节提要本身(CustomGradientBlueView)中UIView的类位置。这可能是个问题。? 这是我用于渐变的代码->

import UIKit

class CustomGradientBlueView: UIView {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    override func drawRect(rect: CGRect) {

        let context = UIGraphicsGetCurrentContext()

        // colour declarations


        let gradientColor1 = UIColor(red: 0.361, green: 0.145, blue: 0.553, alpha: 1.000)
        let gradientColor2 = UIColor(red: 0.263, green: 0.537, blue: 0.635, alpha: 1.000)

        // gradient decalarations

        let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [gradientColor1.CGColor,gradientColor2.CGColor], [0,1])

        //rectangle drawing

        var screen = UIScreen.mainScreen().bounds.size

        let rectanglePath = UIBezierPath(rect: CGRectMake(0,0, screen.width, screen.height))
        CGContextSaveGState(context)
        rectanglePath.addClip()
        CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0 ), CGPointMake(screen.width, screen.height), 0)

    }

}

问题可能出现在以下方面:

var screen = UIScreen.mainScreen().bounds.size
let rectanglePath = UIBezierPath(rect: CGRectMake(0,0, screen.width, screen.height))
CGContextSaveGState(context)
rectanglePath.addClip()
您正在调用
CGContextSaveGState
,而没有调用
CGContextRestoreGState
来平衡它。这是非常危险的。如果上下文得到了维护(这是完全可能的),那么您再次说
addClip
,之前的剪切路径仍然存在-因为您在绘制后没有使用平衡
CGContextRestoreGState
删除它。由于剪切路径的性质,这会导致最终进行整个视图的剪切,并且图形被完全抑制-因此出现黑色视图


(在任何情况下,您都不清楚自己在使用此剪裁路径做什么。不需要剪裁屏幕边界,在视图的
drawRect:
中访问屏幕边界是一件非常奇怪的事情。您可能更乐意删除这四行。)

为什么不使用CAGradientLayer?@MertBuran您能告诉我使用CAGradientLayer如何解决这个问题吗。?区别是什么?“从一些应用程序切换回应用程序后,渐变变为黑色”你能证明,当你这样做时,
drawRect:
被调用吗?@matt我正在使用这个应用程序,然后我切换到Facebook应用程序(比如说任何应用程序)。在使用Facebook很长一段时间后,我回到我的应用程序进行测试,突然它变成了黑色(这是起始页)你没有回答我问的问题。你是对的,matt,我读了文档,了解了这个概念。感谢您宝贵的时间:)我用您建议的代码更改了代码,黑色背景再次出现。