Свойство объекта, содержащее массив, не позволяет мне его сбросить

Редактировать

Я хочу установить границу слева направо

Вам нужно изменить gradient.startPoint и gradient.endPoint

enum Direction {
    case horizontal
    case vertical
}

class View: UIView {

init(frame: CGRect, cornerRadius: CGFloat, colors: [UIColor], lineWidth: CGFloat = 5, direction: Direction = .horizontal) {
    super.init(frame: frame)

    self.layer.cornerRadius = cornerRadius
    self.layer.masksToBounds = true
    let gradient = CAGradientLayer()
    gradient.frame = CGRect(origin: CGPoint.zero, size: self.frame.size)
    gradient.colors = colors.map({ (color) -> CGColor in
        color.cgColor
    })

    switch direction {
    case .horizontal:
        gradient.startPoint = CGPoint(x: 0, y: 1)
        gradient.endPoint = CGPoint(x: 1, y: 1)
    case .vertical:
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 0, y: 1)
    }

    let shape = CAShapeLayer()
    shape.lineWidth = lineWidth
    shape.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth, 
    dy: lineWidth), cornerRadius: cornerRadius).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    self.layer.addSublayer(gradient)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Как вы можете видеть, я добавил некоторые дополнительные параметры. Я решил эту проблему, добавив в нее roundedRect:

shape.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth, 
dy: lineWidth), cornerRadius: cornerRadius).cgPath

Как ее использовать:

let myView = View(frame: CGRect(x: 0, y: 0, width: 200, height: 50), cornerRadius: 25, colors: [UIColor.red, .orange, .yellow], lineWidth: 2, direction: .horizontal)
    myView.center = view.center
    view.addSubview(myView)

Снимок экрана:

roundedViewWithGradient

0
задан divHelper11 18 January 2019 в 19:06
поделиться