ios - 如何以编程方式在 UIPageViewController 中放置自动布局约束?

标签 ios swift autolayout constraints uipageviewcontroller

我正试图在 UIPageViewController 中显示内容,但到目前为止我没有运气。我能够显示页面 View 点,并且背景颜色(蓝绿色)正确应用,但仅此而已。

在我的代码中,我有一个继承自 UIPageViewController 的 PageViewController 和继承自 UIViewController 的 InPageViewController 作为父 View 中的内容页面。

InPageViewController 内部:

    private let labelView: UILabel = {
        let label = UILabel()
//        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Label"

        return label
    }()

    init(data: PageData) {
        super.init(nibName: nil, bundle: nil)
        labelView.text = data.dataName
        view.backgroundColor = .systemTeal
        view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(labelView)

//        These are the constraints I am trying to set. Tried lots of different variations already 
//        NSLayoutConstraint.activate([
//            labelView.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor),
//            labelView.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.centerYAnchor),
//        ])
    }

这是我显示背景颜色而不是标签的当前状态。每当我添加约束数组时,背景就会消失,并恢复为我在 PageViewController 中设置的默认灰色。

    let dataArray = [PageData(dataName: "Data"), PageData(dataName: "Lore")]

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }

    func setupView() {
        title = "A fistful of Datas"
    }

    lazy var arrayInPageViewController: [InPageViewController] = {
        var inPageVC = [InPageViewController]()
        for data in dataArray {
            inPageVC.append(InPageViewController(data: data))
        }
        return inPageVC
    }()

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: .scroll, navigationOrientation: navigationOrientation, options: nil)

        self.dataSource = self
        self.delegate = self

        self.view.backgroundColor = .systemGray
        setViewControllers([arrayInPageViewController[0]], direction: .forward, animated: true, completion: nil)
        print(dataArray)
    }

我在这里设置父 View 。我还有一个扩展,我在其中运行 stub 。

总的来说,我对编程还比较陌生,而且我仍然无法理解 Swift 中的自动布局逻辑,因此非常感谢您的帮助。

最佳答案

您需要将 labelView.translatesAutoresizingMaskIntoConstraints 设置为 false 而不是 view.translatesAutoresizingMaskIntoConstraints

关于ios - 如何以编程方式在 UIPageViewController 中放置自动布局约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58410545/

相关文章:

ios - 使用未解析的标识符 'view'

ios - 我如何知道 handleOpenURL 响应的文档类型?

ios - 将自定义 UIView 锚定到相对于屏幕尺寸的屏幕底部

ios - 为什么我的 UISlider 没有动画?

ios - 我编写仅供个人使用的 iPhone 蓝牙远程控制应用程序的经验

ios - 如何设置自动布局约束,使 UIImageView 的高度等于父 View 的高度?

ios - 使用自动布局扩展为文本的 UITextView

ios - Cordova 深层链接 - 未从通用链接中检测到查询参数

ios - 使用 IB 更改 UISegmented Control 的高度?

swift - Swift 中的局部变量和全局变量