简体   繁体   中英

Add UILabels in swift on viewDidLoad

I am trying to add UILabels programmatically in the viewDidLoad method, below code works when called on a button press but not onViewDidLoad. I want the labels to be display as soon as the view is loaded onto the screen for the first time.

override func viewDidLoad() 
{
        super.viewDidLoad()

        BarGraphView.isRandomColor = true
        let labelsArray:[String] = ["A","B","C","D","E","F","G"]
        var graphPoints: [CGFloat] = [4,8,6,8,5,6,8]

        bar.plotGraph(labelsArray, data: graphPoints)
        lineGraph.plotGraph(labelsArray, data: graphPoints,view: view)

        for i in 0..<lineGraph.graphXAxisPoints.count {

            print("graph x point ==>"+String(lineGraph.graphXAxisPoints.count))
            let labelWidth: CGFloat = 20.0
            var tempLabel  = UILabel()
            print("i value ==>"+String(i))
            var point: CGPoint = CGPoint(x: lineGraph.graphXAxisPoints[i] - labelWidth/2, y: CGFloat( lineGraph.bounds.height - 20) )


            tempLabel.frame = CGRect(origin: point, size: CGSize(width: labelWidth, height: 10))

            tempLabel.textAlignment = NSTextAlignment.Center
            tempLabel.textColor = UIColor.blackColor()
            tempLabel.tag = i+1
            tempLabel.text = labelsArray[i]**


            lineGraph.addSubview(tempLabel)

            let view1 = lineGraph.viewWithTag(i+1)

            lineGraph.addSubview(view1!)

        }


        print("refreshing")
        self.view.setNeedsDisplay()
        lineGraph.setNeedsLayout()
    }

您应该将此代码放在viewWillAppear()然后它应该可以工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM