调整自定义视图的子图层的大小

时间:2017-07-25 09:31:59

标签: swift3

我在UICollectionView内有自定义子图层,但在更改方向时不会调整大小。我知道自动布局不起作用,并发现每当我从超级视图设置布局的框架时,它应该坚持它。下一个解决方案应该是setNeedsLayout()但也不起作用 - 或者我可能将它放在错误的位置。

这是一个画十字架的代码:

func crossLayer(_ view: UIView) {
        let lineColor = UIColor.rgbColor(red: 35, green: 71, blue: 75, alpha: 1.0).cgColor

        var yVerticalStart: CGFloat = 0
        var yVerticalEnd:CGFloat = 0
        var yHorizontalStart: CGFloat = 0
        var yHorizontalEnd:CGFloat = 0

        switch deviceIdiom {
        case .pad:
            yVerticalStart = 20
            yVerticalEnd = frame.height * 0.38 - 20
            yHorizontalStart = frame.height * 0.38 / 2
            yHorizontalEnd = frame.height * 0.38 / 2
        case .phone:
            yVerticalStart = 20
            yVerticalEnd = 130
            yHorizontalStart = 75
            yHorizontalEnd = 75
        default:
            break
        }

        // Vertical line.
        let verticalPath = UIBezierPath()

        // Added 20 points from top side of the view.
        verticalPath.move(to: CGPoint(x: frame.width / 2, y: yVerticalStart))
        verticalPath.addLine(to: CGPoint(x: frame.width / 2, y: yVerticalEnd))

        let verticalLayer = CAShapeLayer()
        verticalLayer.frame = view.bounds

        verticalLayer.path = verticalPath.cgPath
        verticalLayer.lineWidth = 1
        verticalLayer.strokeColor = lineColor

        addSublayer(verticalLayer)

        // Horizontal line.
        let horizontalPath = UIBezierPath()

        // Added 20 points from left side of the view.
        horizontalPath.move(to: CGPoint(x: 20, y: yHorizontalStart))
        horizontalPath.addLine(to: CGPoint(x: frame.width - 20, y: yHorizontalEnd))

        let horizontalLayer = CAShapeLayer()
        horizontalLayer.frame = view.bounds

        horizontalLayer.path = horizontalPath.cgPath
        horizontalLayer.lineWidth = 1
        horizontalLayer.strokeColor = lineColor

        addSublayer(horizontalLayer)
    }

此调用位于方法内的自定义UICollectionView内:

override func draw(_ rect: CGRect) {
        super.draw(rect)
        layer.crossLayer(self)
    }

在VC中 - >

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: nil, completion: {
            _ in
            UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveLinear, animations: {
self.MyCollectionView.layer.layoutSublayers()
                self.MyCollectionView.layer.setNeedsLayout()            })
        })
    }

这些解决方案都不起作用。有什么想法我错过了吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

将以下行添加到crossLayer函数中。

verticalLayer.contentsGravity = kCAGravityResize
horiontalLayer.contentsGravity = kCAGravityResize

它应该可以解决你的问题。

干杯!