ios - 在 UIView 上应用渐变未获得预期结果

标签 ios swift uiview swift2 cagradientlayer

我只是想应用具有 2 个 UIColors 的渐变,这就是我编写以下代码的原因。

class Constants: NSObject {
    class func applyGradient(localView:UIView, color1:UIColor, color2:UIColor) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = localView.bounds
        gradient.colors = [color1.CGColor, color2.CGColor]
        gradient.startPoint = CGPoint(x: 0,y: 0)
        gradient.endPoint = CGPoint(x: 0,y: 1)
        localView.layer.insertSublayer(gradient, atIndex: 0)
        localView.layer.masksToBounds = true
    }
}

并通过以下代码在 UIViewController 的 viewDidLoad 中应用。

Constants.applyGradient(viewContactDetail, color1: gradientColor1, color2: gradientColor2)
Constants.applyGradient(viewDiscountDetail, color1: gradientColor1, color2: gradientColor2)
Constants.applyGradient(viewTermsCondDetail, color1: gradientColor1, color2: gradientColor2)
Constants.applyGradient(viewDiscountAvailDetail, color1: gradientColor1, color2: gradientColor2)

这是我得到的结果

enter image description here

您可以看到,渐变没有正确应用于特定 View 。
我没有发现我的代码有什么问题。

编辑: 这是分层 View 。
enter image description here

最佳答案

试试这个....希望对你有帮助

let gradientLayer = CAGradientLayer()

    gradientLayer.frame = self.shadowview.bounds

    let colorTop = UIColor.green.cgColor
    let colorBottom = UIColor.black.cgColor

    gradientLayer.colors = [colorTop, colorBottom]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.locations = [ 0.0, 1.0]


    self.shadowview.layer.addSublayer(gradientLayer)

enter image description here

关于ios - 在 UIView 上应用渐变未获得预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011902/

相关文章:

ios - 如何从特定索引路径加载 Collection View 单元格?

ios - 我可以在 iOS 中以编程方式设置对象属性吗?

ios - 无法将类型 '[Double]' 的值转换为预期参数类型 'Double'

ios - 为推送通知存储 token

iOS 在键盘之前启动 UIView?

iphone - 如何在IB中使用UIScrollView?

ios - 从 heightForRowAtIndexPath 中调用 cellForRowAtIndexPath — 替代?

swift - 如何访问函数变量并将其从 super View 中删除?

ios - UIView 不会移动到新位置

swift - 如何让用户退出应用程序并返回而不必登录 Firebase