以编程方式创建形状视图并在集合视图单元格上使用

时间:2018-02-05 19:37:36

标签: ios swift uicollectionview uicollectionviewcell cashapelayer

我使用swift以编程方式创建自定义视图。我用CAShapeLayer创建了三角形视图,我在视图控制器上添加了。它工作正常。

但我在集合视图单元格中使用三角形自定义视图,它不起作用。 这是我的自定义视图。如何在集合视图单元格中使用它。

final class CardView: UIView {

    lazy var countLB: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "Helvetica", size: 120)
        label.textColor = UIColor.red
        label.textAlignment = .center
        label.text = "500"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    lazy var topTriangleView: UIView = {
        let view = UIView()
        view.layer.addSublayer(shapeLayer)
        return view
    }()

    lazy var trianglePath: UIBezierPath = {
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 0, y: frame.size.height))
        path.addLine(to: CGPoint(x: frame.size.width, y: 0))
        path.close()
        path.fill()
        return path
    }()

    lazy var shapeLayer: CAShapeLayer = {
        let shape = CAShapeLayer()
        shape.path = trianglePath.cgPath
        shape.fillColor = UIColor.yellow.cgColor
        return shape
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        addSubview(topTriangleView)
        countLB.layer.zPosition = 1
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        assertionFailure()
    }

    private func setupView() {
        addSubview(countLB)
        layer.cornerRadius = 8
        layer.masksToBounds = true
    }

    override func updateConstraints() {
        super.updateConstraints()
        countLB.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        countLB.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    }
}

1 个答案:

答案 0 :(得分:-1)

什么意思"它不起作用"?

您可以查看以下内容:

您应该将CardView实例添加到UICollectionViewCell内的contentView,而不是视图本身。

可能没有调用updateConstraints,你可以添加一个print语句来检查是否存在问题。