How to create a UIScrollView Programmatically?

后端 未结 7 1082
后悔当初
后悔当初 2020-11-30 23:38

Alright, so the key here is I\'m not using IB at all, because the View I\'m working with is created programmatically. The UIView covers the lower half the scre

7条回答
  •  既然无缘
    2020-12-01 00:17

    I use lazy a lot when creating UI programmatically, like this:

    class WorldViewController: UIViewController {
        override func loadView() {
            super.loadView()
            view = scrollView
            scrollView.addSubview(label0)
        }
    
        lazy var scrollView: UIScrollView = {
            let instance = UIScrollView()
            instance.backgroundColor = UIColor.blackColor()
            return instance
        }()
    
        lazy var label0: UILabel = {
            let instance = UILabel()
            instance.text = "Ice caps are melting"
            instance.textColor = UIColor.whiteColor()
            instance.sizeToFit()
            return instance
        }()
    
        var needLayoutContent = true
    
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            if needLayoutContent {
                let bounds = scrollView.bounds
                let contentSize = CGSizeMake(bounds.width * 1.5, bounds.height * 1.5)
                label0.center = CGPointMake(contentSize.width / 2, contentSize.height / 2)
                scrollView.contentSize = contentSize
                scrollView.contentOffset = CGPointMake(bounds.width * 0.25, bounds.height * 0.25)
                needLayoutContent = false
            }
        }
    }
    

提交回复
热议问题