【问题标题】:Swift 4 - How to get bounds of a UIView after Using Constraints ProgramaticallySwift 4 - 如何在以编程方式使用约束后获取 UIView 的边界
【发布时间】:2018-03-08 21:29:14
【问题描述】:

在这个问题上我真的需要你的帮助。我正在以编程方式创建 UIView 对象,而没有在开始时设置边界。创建后,我向该视图添加约束以适应屏幕中所需的位置。

但问题是,我想在代码的以下部分中使用 UIView 的 bounds 属性,但不幸的是,在屏幕上显示的约束设置后,我无法获得边界。

下面我有示例代码:

     let previewView = UIView()

     NSLayoutConstraint(item: previewView, attribute: .top, relatedBy: .equal, toItem: upperView, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true

     NSLayoutConstraint(item: previewView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true


    previewView.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true

    previewView.translatesAutoresizingMaskIntoConstraints = false


    print(previewView.bounds)
   // (0.0, 0.0, 0.0, 0.0) ->>>> How can I get the bounds as it shows on the screen instead of 0,0,0,0

此后,当我尝试使用 previewView.bounds 属性时,它返回我原来的大小为 0。

如何通过相关的约束设置获得屏幕上显示的边界?

非常感谢你们。

【问题讨论】:

  • 调用preview.superview.layoutIfNeeded()后打印边界。

标签: swift autolayout constraints bounds


【解决方案1】:

您可以在

中访问它
 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once { 
        once = false
        // process here
        print(previewView.bounds) 
    } 
 }

但首先将视图声明为实例变量,使once = false 在视图中

var previewView:UIView! 
var once= true

看这里

【讨论】:

  • 嗨,我的朋友,当我尝试您的建议时,我可以得到我所需要的。但这意味着我应该将我的代码从 viewDidLoad 移动到 viewDidLayoutSubviews() 。你觉得这有意义吗?
  • 你是对的。我也在我的 Mac 上尝试了同样的事情 :) 但我无法确定将代码移动到 viewDidLayoutSubviews 是否是一种好方法。你有什么建议?
  • 您可以这样做,但将所有代码包装在 Once bool 变量中,因为此方法被多次调用
  • 啊哈,你的意思是我应该在执行代码之前检查它是否是第一次?
猜你喜欢
  • 2023-04-02
  • 2016-08-07
  • 2015-06-03
  • 2014-11-28
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多