![](/img/trans.png)
[英]How to contraint the bottom edge and top edge of a view to another view in auto layout ios?
[英]How to get bottom edge of the view?
我看了以下文章,以了解如何獲取視圖底部邊緣的y坐標 : 如何獲取底部y坐標
它說我可以做到這一點: exampleView.frame.maxY
但是,當我這樣做時,我得到0。這是我的示例:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let thankYouMessage = UILabel()
self.view.addSubview(thankYouMessage)
thankYouMessage.text = "Thank You for Installing the Keyboard"
thankYouMessage.textAlignment = .Center
thankYouMessage.snp_makeConstraints { (make) -> Void in
make.right.left.top.equalTo(self.view)
make.height.equalTo(self.view.frame.height * 0.2)
}
print(thankYouMessage.frame.maxY)
let enableMessage = UILabel()
self.view.addSubview(enableMessage)
enableMessage.text = "Enable the keyboard here:"
enableMessage.textAlignment = .Center
enableMessage.backgroundColor = UIColor.blackColor()
enableMessage.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.view)
make.top.equalTo(self.view).offset(50)
make.width.equalTo(self.view.frame.width * 0.3)
make.height.equalTo(self.view.frame.height * 0.1)
}
}
print(thankYouMessage.frame.maxY)
返回0。
我不確定為什么會這樣。 我需要對第一個視圖執行某種初始化過程嗎?
在布局遍歷運行之前,不會根據其約束和/或其固有內容大小來更新視圖的框架。 最早可以在視圖控制器中獲取視圖的屏幕框架的方法是viewDidLayoutSubviews
方法。
您可以在請求框架之前在視圖上調用layoutIfNeeded
或sizeToFit
,但是根據情況,如果在viewDidLoad
調用,仍然可能給出錯誤的答案。
發生這種情況的原因是,您使用零幀創建了標簽,並且未在viewDidLoad方法的窗口中將視圖添加到層次結構中。 文檔說的是,在viewDidLoad視圖中僅被加載到內存中。 並在viewWillAppear中將其添加到窗口的層次結構中。 將您的打印內容放在viewWillAppear上進行檢查,或使用框架創建UILabel()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.