我正在开发一个应用程序,它对纵向和横向有不同的UI约束和控制位置。这些都是在故事板上完成的。除此之外,我还根据用户关闭其中一个控件来重新定位控件。我通过抓取viewDidLoad中每个控件的框架来实现这一点。一旦我有了这些值,就很容易重新定位控件,并将它们恢复到取消隐藏时的应有状态。问题是,我需要所有的肖像和风景的框架。这样,我就可以不考虑方向而进行重新定位。
如何通过viewDidLoad获取纵向和横向的控件定位信息?有没有办法做到这一点?
发布于 2015-08-14 13:00:51
向视图添加约束后,视图将根据设备大小和方向重新调整其位置和大小。视图大小的重新调整是在viewDidAppear之后调用的viewDidLayoutSubviews方法中完成的。如果您可以在此方法中注销控件的位置和大小,您将获得更新的(在设备中看到的大小和位置)。
但是这个方法在viewDidAppear之后被多次调用,所以如果你想添加任何东西,我建议在viewDidLoad中添加控件,然后在这个方法中更新位置。
发布于 2015-08-15 09:47:39
在做了更多的工作之后,我想出了这个:
import UIKit
class ViewController: UIViewController {
var pButtonFrame: CGRect!
var lButtonFrame: CGRect!
@IBOutlet weak var testButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "screenRotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func screenRotated() {
//Set this only once, the first time the orientation is used.
if lButtonFrame == nil && UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)
{
lButtonFrame = testButton.frame
}
else if pButtonFrame == nil && UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)
{
pButtonFrame = testButton.frame
}
}
}我设置了一个测试按钮,并使用故事板上的约束对其进行了定位。我在NSNotificationCenter中添加了一个观察者来观察屏幕旋转。我将每个方向的帧存储在CGRect变量中。通过检查nil的每个变量,我可以确保在对屏幕进行任何修改之前,它们只设置一次。这样,如果需要,我可以将这些值恢复为它们的原始值。我可以在这里或者在viewDidLayoutSubviews中设置控件的显示和隐藏。
发布于 2018-02-22 18:07:05
import UIKit
class ViewController: UIViewController {
var pButtonFrame: CGRect!
var lButtonFrame: CGRect!
@IBOutlet weak var btntest: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
screenRotate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func screenRotate() {
//Set this only once, the first time the orientation is used.
if lButtonFrame == nil && UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)
{
lButtonFrame = btntest.frame
}
else if pButtonFrame == nil && UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)
{
pButtonFrame = btntest.frame
}
}
}https://stackoverflow.com/questions/32002061
复制相似问题