简体   繁体   English

UIViewController 内部的 UIScrollView 不水平滚动

[英]UIScrollView inside of UIViewController not scrolling horizontally

I have created a UIScrollView inside of a UIViewController.我在 UIViewController 内部创建了一个 UIScrollView。 I have added a UIView inside of my UIScrollView with one label inside of the UIView.我在 UIScrollView 内部添加了一个 UIView,在 Z02EAEBC8A33E004808C45DF2FCF8 内部添加了一个 label。 The plan is to eventually add 3 very large UIButtons that is why I need a scroll view.计划是最终添加 3 个非常大的 UIButton,这就是我需要滚动视图的原因。 I have not used storyboard and it is done all programmatically.我没有使用过 storyboard ,它都是以编程方式完成的。 I cannot get the UIScrollView to work.我无法让 UIScrollView 工作。

class ChooseCategoryPostViewController: UIViewController, UIScrollViewDelegate {

       let scrollView: UIScrollView = {
       let sv = UIScrollView()
       sv.backgroundColor = .green
       return sv
                     }()

       let myView: UIView = {
       let view = UIView()
       view.backgroundColor = .red
       return view
                    }()

       let test: UILabel = {
          let label = UILabel()
          label.text = "test label"
          label.font = UIFont.boldSystemFont(ofSize: 15)
          label.textAlignment = .center
          return label
      }()


         override func viewDidLoad() {
    view.addSubview(scrollView)
    scrollView.addSubview(myView)
    
    scrollView.anchor(top: topTitle.bottomAnchor, left: nil, bottom: nil, right: nil, paddingTop: 200, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: view.frame.width, height: 200)
    myView.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 1700, height: 200)
    myView.addSubview(test)
    test.anchor(top: myView.topAnchor, left: nil, bottom: nil, right: myView.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)

}

 override func viewDidLayoutSubviews() {
    scrollView.isScrollEnabled = true
    // Do any additional setup after loading the view
    scrollView.contentSize = CGSize(width: view.frame.width, height: 200)
}

You need to make sure that the width of the scroll view contentSize is greater than the width of the scroll view itself.您需要确保滚动视图contentSize的宽度大于滚动视图本身的宽度。 Something as simple as the following should cause horizontal scrolling to happen:像下面这样简单的事情应该会导致水平滚动发生:

override func viewDidLayoutSubviews() {
    scrollView.isScrollEnabled = true
    // Do any additional setup after loading the view
    scrollView.contentSize = CGSize(width: view.frame.width * 2, height: 200)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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