将 UIButton 的 CenterYAnchor 对齐到 UIPageControl Swift

Line up CenterYAnchor of UIButton to UIPageControl Swift

我有一些代码,我将 "close" UIButton 添加到 UIPageController.view,效果很好。

工作代码:

class func closeButton(_ pageController: UIPageViewController) -> UIButton {

    let button = UIButton()

    button.setTitleColor(UIColor.white, for: UIControlState())
    button.setTitle("Close", for: UIControlState())
    button.titleLabel!.font = UIFont.systemFont(ofSize: 15)
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
    button.translatesAutoresizingMaskIntoConstraints = false

    pageController.view.addSubview(button)

    button.widthAnchor.constraint(equalToConstant: 50).isActive = true
    button.heightAnchor.constraint(equalToConstant: 36).isActive = true
    button.trailingAnchor.constraint(equalTo: pageController.view.trailingAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: pageController.view.bottomAnchor).isActive = true

    return button
}

但后来我在 iPhone X 模拟器上测试了我的代码,UIPageControl 比其他 iPhone 离底部高得多。所以现在我刚刚添加的关闭按钮位于底部圆角并且 UIPageControl 高得多。

然后我尝试引用 UIPageControl 与:

let pageControl: UIPageControl = UIPageControl.appearance()

然后将 button.bottomAnchor.constraint... 替换为:

button.centerYAnchor.constraint(equalTo: pageControl.centerYAnchor).isActive = true

但这会导致抛出错误。我尝试打印 UIPageControl.frame,它是 0,0,0,0。所以我假设这与它有关。

有没有办法对 UIPageControl 进行约束?

如果您使用的是自定义视图,请尝试在 layoutSubviews() 方法或视图控制器的 viewDidLayoutSubviews() 方法中更新您的约束:

func layoutSubviews() {
    super.layoutSubviews()
    button.centerYAnchor.constraint(equalTo: pageControl.centerYAnchor).isActive = true
}