[英]How to add auto layout constraints to UINavigationBar programmatically
[英]How to place auto layout constraints inside UIPageViewController programmatically?
我試圖在 UIPageViewController 中顯示內容,但到目前為止我還沒有運氣。 我能夠顯示頁面視圖點,並且背景顏色(藍綠色)正確應用,但僅此而已。
在我的代碼中,我有一個繼承自 UIPageViewController 的 PageViewController 和繼承自 UIViewController 的 InPageViewController 作為父視圖內的內容頁面。
在 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),
// ])
}
這是我用來顯示背景顏色的當前 state,但不是 label。 每當我添加約束數組時,背景就會消失,並恢復為我在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)
}
在這里,我正在設置父視圖。 我還有一個擴展,我在其中運行存根。
一般來說,我對編程比較陌生,我仍然無法理解 Swift 中的自動布局邏輯,因此不勝感激。
您需要將labelView.translatesAutoresizingMaskIntoConstraints
設置為false
而不是view.translatesAutoresizingMaskIntoConstraints
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.