【问题标题】:UIScrollView inside of UIViewController not scrolling horizontallyUIViewController 内的 UIScrollView 不水平滚动
【发布时间】:2020-11-19 17:17:35
【问题描述】:

我在 UIViewController 中创建了一个 UIScrollView。我在 UIScrollView 中添加了一个 UIView,在 UIView 中添加了一个标签。计划是最终添加 3 个非常大的 UIButton,这就是我需要滚动视图的原因。我没有使用故事板,它都是以编程方式完成的。我无法让 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)
}

【问题讨论】:

  • 你也许可以在你的 ScrollView 中添加一个 Horizo​​ntal StackView。然后在 StackView 中添加标签和按钮
  • 我试了还是不能滚动。
  • 您在设置滚动视图的内容大小时是否仔细检查了view.frame.width 是什么?如果您使用的是程序化自动布局,我相信在滚动视图的 contentLayoutGuide 上设置约束是可行的方法,我不确定这里使用的非标准 anchor 函数是否可以做到这一点。跨度>
  • 这是因为你的内容尺寸宽度小于或等于滚动视图的宽度。您需要使内容大小宽度大于滚动视图宽度

标签: ios swift uiscrollview


【解决方案1】:

您需要确保滚动视图contentSize 的宽度大于滚动视图本身的宽度。像下面这样简单的事情应该会导致水平滚动:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多