Disable horizontal scroll in UIScrollView with autolayout

前端 未结 2 1339
猫巷女王i
猫巷女王i 2021-02-04 00:38

I want to create view with only vertical scroll. As it turned out it is epic hard to do in iOs. I have done this steps:

1) Create UIViewController in storyboard;

2条回答
  •  情歌与酒
    2021-02-04 00:50

    You can also easily do this in code. In my case, I have a UIStackView that's the only subview of a UIScrollView

    // Create the stack view
    let stackView = UIStackView()
    stackView.translatesAutoresizingMaskIntoConstraints = false
    // Add things to the stack view....
    
    // Add it as a subview to the scroll view
    scrollView.addSubview(stackView)
    
    // Use auto layout to pin the stack view's sides to the scroll view
    NSLayoutConstraint.activate([
        stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor),
    
        stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: stackView.bottomAnchor)
    ])
    
    // Now make sure the thing doesn't scroll horizontally
    let margin: CGFloat = 40
    
    scrollView.contentInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
    
    scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    
    let stackViewWidthConstraint = stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
    stackViewWidthConstraint.constant = -(margin * 2)
    stackViewWidthConstraint.isActive = true
    

    The NSLayoutConstraint.activate bit is taken from Dave DeLong's excellent UIView extension here: https://github.com/davedelong/MVCTodo/blob/master/MVCTodo/Extensions/UIView.swift#L26

提交回复
热议问题