带编程的AutoLayouts UIScrollView

时间:2018-04-06 12:40:31

标签: ios swift uiscrollview autolayout

我有一个UIScrollView,我想垂直滚动。我正在以编程方式创建UIScrollView并面临自动布局的问题。

我已将单个子项添加到UIScrollView中,其余控件已添加到该子视图中。

以下代码会创建滚动视图的UIScrollViewcontentView

lazy var scrollView : UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.keyboardDismissMode = .onDrag
   // scrollView.backgroundColor = .red
    return scrollView
}()

let contentView: UIView = {
    let contentV = UIView()
    contentV.translatesAutoresizingMaskIntoConstraints = false
    contentV.backgroundColor = UIColor.yellow
    return contentV
}()

以下代码会在UIScrollView内的viewcontentView内添加UIScrollView

view.addSubview(scrollView)

    scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8).isActive = true

//内容视图

scrollView.addSubview(contentView)

    contentView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true


    contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
    contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true

    contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

执行此操作后,我尝试在contentView上添加其他控件但我的view未正确显示,请参阅以下内容image我已搜索了许多教程,以编程方式添加滚动视图但是无法这样做。

0 个答案:

没有答案