添加到Stackview子视图的CAShapeLayers仅在一个子视图上呈现

时间:2018-07-23 14:00:44

标签: ios swift

calorieViewtimeView应该显示一个黑色圆圈。但 distanceView显示预期的黑色圆圈。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a
        let allViews: [UIView] = [distanceView, calorieView, timeView]
        let stackView = UIStackView(arrangedSubviews: allViews)
        stackView.frame = view.frame
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.spacing = 0
        let y1 = CGFloat(0)
        let y2 = view.frame.height / 3
        let y3 = y2 * 2
        distanceView.frame = CGRect(x: 0, y: y1, width: view.frame.width, height: y2)
        calorieView.frame = CGRect(x: 0, y: y2, width: view.frame.width, height: y2)
        timeView.frame = CGRect(x: 0, y: y3, width: view.frame.width, height: y2)
        distanceView.layer.addSublayer(self.createViewLayer(localView:    distanceView))
        calorieView.layer.addSublayer(self.createViewLayer(localView: calorieView))
        timeView.layer.addSublayer(createViewLayer(localView: timeView))
        view.addSubview(stackView)

    }


    func createCircleLayer(center: CGPoint, radius: CGFloat, clockWise:Bool) -> CAShapeLayer {
        let shapeLayer = CAShapeLayer()

        let path = UIBezierPath
         (arcCenter: center, radius: radius, startAngle: 0,
         endAngle: 2 *     CGFloat.pi, clockwise: clockWise)
        shapeLayer.path = path.cgPath

        return shapeLayer
    }

    func createViewLayer(localView: UIView) -> CAShapeLayer {
        print(localView)
        var viewLayer = CAShapeLayer()
        viewLayer.frame = localView.frame
        let center = localView.center
        print(center)
        let radius = localView.frame.height / 3
        let isClockwise = true
        viewLayer = self.createCircleLayer
        (center: center, radius: radius, clockWise: isClockwise)
        return viewLayer
    }

}

1 个答案:

答案 0 :(得分:1)

您在做的错误是为视图设置y坐标,基本上完成了垂直UIStackView会做的工作。

使用堆栈视图时,所有视图都应将xy坐标设置为0,0,因为将UIStackView定位到arrangedViews根据它的设置。

只需将帧更改为具有origin = (0,0)或不使用UIStackView并使用计算出的y坐标...