我正试图在 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/