我试图应用渐变作为一个视图(故事板的主视图)的背景色。代码运行,但没有任何变化。我使用xCode Beta 2和Swift。

代码如下:

class Colors {
  let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
  let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)

  let gl: CAGradientLayer

  init() {
    gl = CAGradientLayer()
    gl.colors = [ colorTop, colorBottom]
    gl.locations = [ 0.0, 1.0]
  }
}

然后在视图控制器中:

  let colors = Colors()

  func refresh() {
        view.backgroundColor = UIColor.clearColor()
        var backgroundLayer = colors.gl
        backgroundLayer.frame = view.frame
        view.layer.insertSublayer(backgroundLayer, atIndex: 0)
      }
    }
  }

当前回答

使用以下代码:

extension UIView {
func applyGradient(colours: [UIColor]) -> Void {
 let gradient: CAGradientLayer = CAGradientLayer()
 gradient.frame = self.bounds
 gradient.colors = colours.map { $0.cgColor }
 gradient.startPoint = CGPoint(x : 0.0, y : 0.5)
 gradient.endPoint = CGPoint(x :1.0, y: 0.5)
 self.layer.insertSublayer(gradient, at: 0)
 }
}

像这样调用这个函数:

  self.mainView.applyGradient(colours: [.green, .blue])

其他回答

下面是在可重用的Util类文件中进行设置的变体

在你的Xcode项目中:

Create a new Swift class call it UI_Util.swift, and populate it as follows: import Foundation import UIKit class UI_Util { static func setGradientGreenBlue(uiView: UIView) { let colorTop = UIColor(red: 15.0/255.0, green: 118.0/255.0, blue: 128.0/255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 84.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0).cgColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorTop, colorBottom] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = uiView.bounds uiView.layer.insertSublayer(gradientLayer, at: 0) } }


现在你可以像这样从任何ViewController调用这个函数: 类AbcViewController: UIViewController override func viewDidLoad() { super.viewDidLoad () UI_Util。setGradientGreen (uiView self。view): }

感谢katwal-Dipak对函数代码的回答

SwiftUI:你可以使用线性梯度结构作为ZStack的第一个元素。作为ZStack的“底部”,它将作为背景色。AngularGradient和RadialGradient也可用。

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom)
                .edgesIgnoringSafeArea(.all)
            // Put other content here; it will appear on top of the background gradient
        }
    }
}

对于那些想要Objective C版本的答案的人。经过测试,在iOS13上运行

// Done here so that constraints have completed and the frame is correct.
- (void) viewDidLayoutSubviews { 
    [super viewDidLayoutSubviews];
    UIColor *colorTop = [UIColor colorWithRed:(CGFloat)192.0/255.0 green: 38.0/255.0 blue: 42.0/255.0 alpha:1.0];
    UIColor *colorBottom = [UIColor colorWithRed: 35.0/255.0 green: 2.0/255.0 blue: 2.0/255.0 alpha: 1.0];
    CAGradientLayer *gl = [CAGradientLayer new];
    [gl setColors:@[(id)[colorTop CGColor], (id)[colorBottom CGColor]]];
    [gl setLocations:@[@0.0f, @1.0f]];
    self.view.backgroundColor = [UIColor clearColor];
    CALayer *backgroundLayer = gl;
    backgroundLayer.frame = self.view.frame;
    [self.view.layer insertSublayer:backgroundLayer atIndex:0];
}

用这个自定义类扩展UIView。


GradientView.swift

import UIKit

class GradientView: UIView {

    // Default Colors
    var colors:[UIColor] = [UIColor.redColor(), UIColor.blueColor()]

    override func drawRect(rect: CGRect) {

        // Must be set when the rect is drawn
        setGradient(colors[0], color2: colors[1])
    }

    func setGradient(color1: UIColor, color2: UIColor) {

        let context = UIGraphicsGetCurrentContext()
        let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [color1.CGColor, color2.CGColor], [0, 1])!

        // Draw Path
        let path = UIBezierPath(rect: CGRectMake(0, 0, frame.width, frame.height))
        CGContextSaveGState(context)
        path.addClip()
        CGContextDrawLinearGradient(context, gradient, CGPointMake(frame.width / 2, 0), CGPointMake(frame.width / 2, frame.height), CGGradientDrawingOptions())
        CGContextRestoreGState(context)
    }

    override func layoutSubviews() {

        // Ensure view has a transparent background color (not required)
        backgroundColor = UIColor.clearColor()
    }

}

使用

gradientView。colors = [uiccolor . blackcolor ().colorWithAlphaComponent(0.8), uiccolor . clearcolor ()]


结果

在Swift3试试这个:

 func addGradient(){

    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.frame.size = self.viewThatHoldsGradient.frame.size
    gradient.colors = [UIColor.white.cgColor,UIColor.white.withAlphaComponent(0).cgColor] //Or any colors
    self.viewThatHoldsGradient.layer.addSublayer(gradient)

}