在呈现的视图控制器中以编程方式添加子视图

Adding subviews programmatically in presented view controller

问题

子视图以编程方式添加到 containerView(UIView,它与故事板上的@IBOutlet 连接)在呈现的直方图ViewController(ViewController) 布局不当。

代码和评论

直方图ViewController

class HistogramViewController: UIViewController {
    
    @IBOutlet weak var containerView: UIView!
 
    var dataPoints: [[Int]]?
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .gray
      
        let chart_axes = ChartAxes(frame: containerView.frame)
        chart_axes.backgroundColor = UIColor.red.withAlphaComponent(0.6)
        containerView.addSubview(chart_axes)

    }

containerView 具有常量值:400 宽度,600 高度设置在 Storyboard 的约束中

ChartAxes(UIView 添加到 HistogramVC 中的 containerView)

extension HistogramViewController {
    
    private class ChartAxes : UIView{
        
        override func draw(_ rect: CGRect) {
            do{
               // self.backgroundColor = UIColor.clear.withAlphaComponent(0)
                let start = CGPoint(x:rect.origin.x,y:rect.origin.y)
                let joint = CGPoint(x:0,y:rect.height)
                let end = CGPoint(x:rect.width,y:rect.height)
                let axes = UIBezierPath()
                axes.move(to: start)
                axes.addLine(to: joint)
                axes.addLine(to: end)
                axes.lineWidth = 5.0
                UIColor.white.setStroke()
                axes.stroke()
            }
        }
    }

它基本上是从左上角,通过左下角到右下角的路径——就像图表中的轴

目前的结果(不应该是这样的!)

红色区域应与黑色containerView 大小相同。是否与函数 present(ViewController ) ?

相关联
   guard let controller = storyboard?.instantiateViewController(withIdentifier: "HistogramViewController") as? HistogramViewController else{ return }
           // controller.modalPresentationStyle = .overFullScreen
            present(controller,animated: true)

viewDidLoad containerView.frame 的值不准确 实施

var chart_axes:ChartAxes!

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   chart_axes.frame = containerView.frame
}

或设置约束条件

let chart_axes = ChartAxes(frame: containerView.frame)
chart_axes.backgroundColor = UIColor.red.withAlphaComponent(0.6)
containerView.addSubview(chart_axes)   
chart_axes.translatesAutoresizingMaskIntoConstraints = false 
NSLayoutConstraint.activate([
  chart_axes.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
  chart_axes.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
  chart_axes.topAnchor.constraint(equalTo: containerView.topAnchor),
  chart_axes.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) 
])