如何在 Xcode 中以编程方式制作滚动视图并在其中添加视图



我想在 xcode 中以编程方式制作滚动视图,并希望使用安全区域布局指南自动布局添加锚点约束。并且想添加一些文本视图按钮和地图初始化,但找不到任何适当的方法来执行此操作。我尝试了很多代码。正确的代码是什么?

请尝试以下代码以编程方式创建Scroll view并在XCode中添加UIView

斯威夫特 4.0

import UIKit
class ViewController: UIViewController {
    let scrollView: UIScrollView = {
        let view = UIScrollView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    let myView: UIView = {
        let view = UIView()
        view.backgroundColor = .yellow
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        // add the scroll view to self.view
        self.view.addSubview(scrollView)
        
        // constrain the scroll view to 8-pts on each side
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8.0).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8.0).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8.0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8.0).isActive = true
        
        //Frame for UIView here
        myView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
        scrollView.addSubview(myView)
    }
}

最新更新