我正在研究具有不同UI约束和纵向和横向控件位置的应用程序。这些都是在故事板上完成的。除此之外,我基于用户关闭其中一个控件来重新定位控件。我通过抓取viewDidLoad中每个控件的框架来完成此操作。一旦我有了这些值,那么很容易重新定位控件并将它们恢复到未隐藏状态时的状态。问题是我需要纵向和横向的所有帧。这样我可以不管方向如何重新定位。纵向和横向获取控件的原始框架
如何通过viewDidLoad获取纵向和横向的控制定位信息?有没有办法做到这一点?
我正在研究具有不同UI约束和纵向和横向控件位置的应用程序。这些都是在故事板上完成的。除此之外,我基于用户关闭其中一个控件来重新定位控件。我通过抓取viewDidLoad中每个控件的框架来完成此操作。一旦我有了这些值,那么很容易重新定位控件并将它们恢复到未隐藏状态时的状态。问题是我需要纵向和横向的所有帧。这样我可以不管方向如何重新定位。纵向和横向获取控件的原始框架
如何通过viewDidLoad获取纵向和横向的控制定位信息?有没有办法做到这一点?
向视图添加约束条件后,视图会根据设备大小和方向重新调整其位置和大小。视图大小的重新调整在的方法中完成,该方法在viewDidAppear
之后调用。 如果您可以在此方法中注销控件的位置和大小,您将获得更新(尺寸和位置,如在设备中所见)。
但是这种方法在viewDidAppear
之后被多次调用,所以如果你想添加任何东西,我推荐在viewDidLoad
中添加控件,然后在这个方法中更新位置。
这个工作多一点后,我想出了这个:
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
变量中存储每个方向的帧。通过检查每个变量为零,我可以确保他们只有一次设置,在我做了任何修改屏幕之前。这样,如果需要,我可以将这些值恢复到原始值。我可以在这里设置控件的显示和隐藏,或者在viewDidLayoutSubviews
。
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
}
}
}
这绝对给了我一些关于如何解决这个问题的想法。今晚我有机会尝试这个之后,我会回复。 –