ios - 在 UIScrollView 中滚动一个 UIView

标签 ios iphone swift uiview uiscrollview

很多问题都与此有关,但我对约束非常不满意。所以我添加了一个 UIScrollView 并且我想显示的 UIView 的高度为 700 并且这是固定的 700 没有动态高度。我对 UIScrollView 的约束是:

enter image description here

UIView 的约束是:

enter image description here

但它没有滚动。

最佳答案

当我需要一个可滚动的 View 时,我所做的如下 - 只需在 Storyboard 中检查你的约束并在那里做同样的事情(特别注意第二步):

  1. 我将 scrollView 添加到层次结构中并使用自动布局对其进行适当布局,例如,如果它应该覆盖 的整个 view > View Controller :

    scrollView.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
        scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
        scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
    ])
    
  2. 然后你需要在 scrollView 中添加一个 contentView 并为其提供适当的布局约束,所以如果你想要垂直滚动 scrollView 在我上面开始的示例中,您需要遵循自动布局约束:

    contentView.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        // horizontal anchors of contentView are constrained to scrollView superview
        // to prevent it from scrolling horizontally
        contentView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
        contentView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
        // but vertical anchors of contentView are constrained to
        // scrollView to allow scrolling
        contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
        contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
    ])
    

    请注意,我将 contentViewleftAnchorrightAnchor 约束到 self.view 而不是到 scrollView 使其具有固定宽度。但是,顶部和底部 anchor 被限制在 ScrollView 中,因此当 contentView 需要更多空间时,它们会展开并可滚动。

  3. 现在您向 contentView 添加您想要的所有内容,并使用自动布局对其进行布局,就像 contentView 是一个具有无限高度的 View 一样.或者您可以根据需要将其高度显式设置为 700。

关于ios - 在 UIScrollView 中滚动一个 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48321859/

相关文章:

iOS 和数据库

iphone - 如何使用 UIPickerView

iphone - 创建指向对象的指针后删除对象 [Objective-C]

iphone - 在设备上拖动/调整 UIImage 的大小

swift - 谁能解释一下如何在不使用 cocoapods 的情况下通过 swift 在 iOS 上集成 Google Analytics?

ios - 来自 URL 的图像不遵循 Storyboard 中的样式规则

ios - 符合类扩展的协议(protocol)

ios - 快速点击条形按钮项目时 UIFont 发生变化

ios - 自动登录,AppDelegate 为 SceneDelegate,UIApplication.shared.delegate 为! AppDelegate 被替换为?

swift - 在打印时显示的 TextView 中可选