我想添加一个渐变视图。但它并没有占据整个宽度。我该如何解决这个问题?
我在这里分享我的代码
import UIKit
import SwiftHEXColors
extension UIView {
func applyGradient(isVertical: Bool, colorArray: [UIColor]) {
layer.sublayers?.filter({ $0 is CAGradientLayer }).forEach({ $0.removeFromSuperlayer() })
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colorArray.map({ $0.cgColor })
if isVertical {
//top to bottom
gradientLayer.locations = [0.0, 1.0]
} else {
//left to right
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
}
backgroundColor = .clear
gradientLayer.frame = self.bounds
layer.insertSublayer(gradientLayer, at: 0)
// layer.masksToBounds = true
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
func applyAPPGradient() {
self.applyGradient(isVertical: true, colorArray: [
UIColor(red: 0.039, green: 0.318, blue: 0.631, alpha: 1),
UIColor(red: 0.02, green: 0.161, blue: 0.318, alpha: 1)
])
}
}
您的代码可能在渲染之前和计算正确宽度之前调用(可能您的 UI 在 iPhone 14 pro 上,而您在模拟器中的渲染在 iPhone 14 pro MAX 上)
您可以在
中添加代码DispatchQueue.main.async {
... your Gradient Code
}
或
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
... your Gradient Code
}
此代码(延迟)有助于首先执行渲染,然后计算正确的宽度