在 Swift 3 中以编程方式使用 ScrollView

2024-02-26

我搜索了其他问题,似乎在 swift 3 中使用自动布局以编程方式创建滚动视图时仍然遇到一些问题。我能够让我的滚动视图显示如下图所示,但是当我滚动到底部时,我的其他标签却出现了问题不显示,“滚动顶部”标签也不会消失。

希望有人可以帮助查看我下面的代码!

import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()


override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)


    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)     

    }

}

使用约束来定义滚动内容大小很容易 - 因此您无需进行任何手动计算。

只要记住:

  1. The 内容元素滚动视图的必须具有左/顶部/宽度/高度值。对于标签等对象,它们具有固有尺寸,因此您只需定义左侧和顶部。
  2. The 内容元素你的滚动视图also定义可滚动区域的边界 -contentSize- 但他们这样做是有底部和右侧约束的。
  3. 结合这两个概念,您会发现您需要一个“连续链”,其中至少有一个元素定义顶部/左侧/底部/右侧范围。

这是一个简单的示例,它将直接在 Playground 页面中运行:

import UIKit
import PlaygroundSupport

class TestViewController : UIViewController {

    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .red
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add the scroll view to self.view
        self.view.addSubview(scrollView)
        
        // constrain the scroll view to 8-pts on each side
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8.0).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8.0).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8.0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8.0).isActive = true
        
        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)
        
        // constrain labelOne to left & top with 16-pts padding
        // this also defines the left & top of the scroll content
        labelOne.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 16.0).isActive = true
        labelOne.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16.0).isActive = true
        
        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)
        
        // constrain labelTwo at 400-pts from the left
        labelTwo.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 400.0).isActive = true

        // constrain labelTwo at 1000-pts from the top
        labelTwo.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 1000).isActive = true
        
        // constrain labelTwo to right & bottom with 16-pts padding
        labelTwo.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -16.0).isActive = true
        labelTwo.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -16.0).isActive = true
        
    }
    
}


let vc = TestViewController()
vc.view.backgroundColor = .yellow
PlaygroundPage.current.liveView = vc

Edit- 由于这个答案仍然偶尔受到关注,我已经更新了代码以使用更现代的语法,尊重安全区域,并使用滚动视图.contentLayoutGuide:

class TestViewController : UIViewController {
    
    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .yellow
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add the scroll view to self.view
        self.view.addSubview(scrollView)

        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)
        
        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)
        
        // always a good idea to respect safe area
        let safeG = view.safeAreaLayoutGuide
        
        // we want to constrain subviews to the scroll view's Content Layout Guide
        let contentG = scrollView.contentLayoutGuide
        
        NSLayoutConstraint.activate([
            
            // constrain the scroll view to safe area with 8-pts on each side
            scrollView.topAnchor.constraint(equalTo: safeG.topAnchor, constant: 8.0),
            scrollView.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 8.0),
            scrollView.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -8.0),
            scrollView.bottomAnchor.constraint(equalTo: safeG.bottomAnchor, constant: -8.0),
            
            // constrain labelOne to leading & top of Content Layout Guide with 16-pts padding
            // this also defines the left & top of the scroll content
            labelOne.topAnchor.constraint(equalTo: contentG.topAnchor, constant: 16.0),
            labelOne.leadingAnchor.constraint(equalTo: contentG.leadingAnchor, constant: 16.0),

            // constrain labelTwo leading at 400-pts from labelOne trailing
            labelTwo.leadingAnchor.constraint(equalTo: labelOne.trailingAnchor, constant: 400.0),
            
            // constrain labelTwo top at 1000-pts from the labelOne bottom
            labelTwo.topAnchor.constraint(equalTo: labelOne.bottomAnchor, constant: 1000),
            
            // constrain labelTwo to trailing & bottom of Content Layout Guide with 16-pts padding
            // this also defines the right & bottom of the scroll content
            labelTwo.trailingAnchor.constraint(equalTo: contentG.trailingAnchor, constant: -16.0),
            labelTwo.bottomAnchor.constraint(equalTo: contentG.bottomAnchor, constant: -16.0),
            
        ])
        
    }
    
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swift 3 中以编程方式使用 ScrollView 的相关文章

随机推荐

  • 用于在基于着色器的游戏中进行渲染的 OO 架构

    在构建游戏引擎时 我一直遇到这个问题 我的类希望看起来像这样 interface Entity draw class World draw for e in entities e draw 这只是伪代码 大致展示了绘图是如何发生的 每个实体
  • 错误:无法使用 Google Cloud Function 和 Express 处理请求

    这是我的代码 为什么当我访问云函数的 url 时 我收到此消息 错误 无法处理请求 但没有看到 Hello World 谢谢 exports simple req res gt var express require express var
  • 如何使用新语法[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 如何使用 C++ 在 Windows 上创建具有 UNICODE 路径的文件

    我想知道哪个 Win32 API 调用正在创建具有 UNICODE 路径的文件 只是为了确保 我在这里谈论的不是内容 而是文件路径 如果有人能用 MSDN 网址打我 我将不胜感激 这次我的 google fu 失败了 预先感谢一百万 See
  • R CRAN 检查中的注意事项 -- * 检查顶级文件... 注意 如果未安装“pandoc”,则无法检查文件 README.md

    我正在检查我的 R 包是否有 CRAN 提交 但有一个注释我无法删除 我用谷歌搜索了它 但似乎这个注释并不常见 因此我没有找到太多有用的信息 任何人都可以为我提供解决方案吗 以下是输出的一部分R CMD check as cran usin
  • 异常后重置 Cuda 上下文

    我有一个使用 Cuda C 的工作应用程序 但有时 由于内存泄漏 会引发异常 我需要能够实时重置 GPU 我的应用程序是服务器 因此它必须保持可用 我尝试过类似的方法 但似乎不起作用 try do process using GPU cat
  • ifstream 相当于 FILE * 的倒回方法

    我的任务是将一些 C 代码更新为 C 并且很好奇 ifstream 中 C FILE 的倒带方法的等效方法或实现是什么 那将是seekg http en cppreference com w cpp io basic istream see
  • 通过另一个列表过滤一个列表 C#

    我有以下业务对象 public class ItemCategoryBO public string ItemCategory get set public string Title get set public class ItemBO
  • 填充 std::tuple

    我有一个重载函数 如下所示 template
  • Javascript 获取 Flask json

    所以我试图将 Flask 服务器连接到前端创建反应应用程序 现在我只想验证我是否可以在两者之间发送 json 下面是每个错误的代码以及更多关于错误的描述 创建 React App 获取 import React Component from
  • 使用 Networkx 绘制带边的图

    我一直被一件很简单的事情所困扰 我正在尝试绘制并显示一个具有 2 个节点和 1 个边的图 但我收到这个错误 Traceback most recent call last File
  • 安装 MySQL-python

    我在尝试在我的 Ubuntu Linux Box 上安装 MySQL python 时遇到以下失败 从下面来看 问题似乎是sh mysql config not found有人可以建议我该怎么做吗 rmicro ubuntu pip ins
  • CSS 类定义在 元素内不起作用

    你们能告诉我为什么 css 类定义在下面的示例中不起作用吗 我正在使用 GWT 2 4 Chrome 17
  • 历史推送状态和滚动位置

    当用户使用 HTML5 popstate 处理程序导航回浏览器历史记录时 我尝试检索滚动位置 这是我所拥有的 document ready function window on popstate PopStateHandler link c
  • 是否可以像来自用户一样向 Bot Framework 发送消息?

    我正在使用 Direct Line 3 0 和 Microsoft Bot Framework 并要求网页将一些表单字段发送到机器人 就像用户发送它们一样 例如 当用户按下 提交 时 电子邮件 电话等字段将被发送到机器人 就像用户这样发送它
  • 获取精灵部分偏移量

    我正在尝试获取 elf 文件每个部分的偏移量和数据 我已经有了包含以下代码的部分名称 include
  • Python - 保存在 GNU Nano 2.2.4 中编辑的文件[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我对编程 使用 Raspberry
  • 调试 Outlook 插件桌面

    我目前正在使用 yeoman 和生成器办公室为 Outlook 开发一个插件 以将电子邮件及其附件保存到另一项服务 Outlook 版本 MS Office Professional Plus 2016 v 16 0 48 49 1000
  • 提交表单时,表单 onSubmit 函数不会触发

    我看过了 找不到任何像我的问题一样的东西 我有一个表格无法进行验证 我知道 JavaScript 文件正在加载 因为页面上的其他功能正在正常工作 我的代码如下
  • 在 Swift 3 中以编程方式使用 ScrollView

    我搜索了其他问题 似乎在 swift 3 中使用自动布局以编程方式创建滚动视图时仍然遇到一些问题 我能够让我的滚动视图显示如下图所示 但是当我滚动到底部时 我的其他标签却出现了问题不显示 滚动顶部 标签也不会消失 希望有人可以帮助查看我下面