如何使用 Swift 正确定位 UIView



我读了很多与我的问题相似的问题的答案。但仍然无法弄清楚我遇到的这个问题。

我正在将UIView添加到另一个UIView之上。

    @IBOutlet weak var contentView: UIView!

以下是我在内容视图之上添加另一个视图的方法。

 func showPopupView(){
    popupView.bounds.size.width = contentView.bounds.size.width
    popupView.bounds.size.height = self.view.frame.height - 99
    popupView.frame.origin.y = contentView.frame.origin.y + 50
    popupView.center.x = contentView.center.x
    view.addSubview(popupView)
}

我计算 99 为 49 + 50。 49 是 TabBar 高度,50 是顶部视图的高度。

但是,弹出窗口视图不会在所有模拟器大小上按预期显示。它在iPhone SE上按预期显示,但在iPhone 6,iPhone 6s或iPhone X上存在差距。

我应该如何在超级视图(self.view(上定位弹出视图?

我终于设法通过以下代码在所有设备类型上正确定位我的弹出窗口视图。

func showPopupView(){
    let statusBarHeight = self.view.safeAreaInsets.top
    showPopupView.frame.size.width = contentView.frame.size.width
    showPopupView.frame.size.height = contentView.frame.height
    showPopupView.frame.origin.y = contentView.frame.origin.y + statusBarHeight
    showPopupView.center.x = contentView.center.x
    view.addSubview(showPopupView)
}

使用此代码,popupView 获取contentView的高度和宽度。考虑到statusBarHeight,将自己定位在当前视图的顶部。

你的方法在几个层面上是错误的。

  1. 你的代码中有几个"幻数">

  2. 您正在操纵视图的框架。别这样。自动布局可能会破坏您的尺寸和展示位置。而是创建自动布局约束(查看布局锚点。它们非常易于使用。

强烈建议使用autolayout,而不是硬编码:

class SomeController: UIViewController {
    @IBOutlet weak var contentView: UIView!
    func showPopupView() {
        let popupView = UIView()   // or any other way how your `popupView` should be initialized
        view.addSubview(popupView) // Adding popup view before the setting anchors
        popupView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)   // constant is 0 by default, could be any else
        popupView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) // constant is 0 by default, could be any else
        popupView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 50) // same top position as `contentView`'s top plus 50 points
        popupView.heightAnchor.constraint(equalTo: contentView.heightAnchor, constant: -100) // same haight as `contentView`'s haight minus 100 points
    }
}

注意:我假设contentViewview的子视图。此外,在使用anchors之前,应将popupView添加到子视图中。

你可以

尝试这样的事情

  NSLayoutConstraint.activate([
    popupView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 50),
    popupView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
    popupView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
    ])
   if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
    popupView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)])
 } else {
    NSLayoutConstraint.activate([
    popupView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor)])
}

最新更新