当我将设备从纵向旋转到横向时,我的问题就在这里我的自定义uiview不会改变它们的宽度和高度。因此,当设备在横向上时,它仍然可以获得设备在纵向上的宽度和高度。到目前为止,这是我的代码:
import UIKit
class BasicView: UIView {
let centerView: UIView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged", name: UIDeviceOrientationDidChangeNotification, object: nil)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func layoutSubviews() {
super.layoutSubviews()
print("orientation or other bounds-impacting change")
}
func orientationChanged() {
centerView.frame = CGRectMake(0, 0,556.0,290.0);
}
func setupView() {
centerView.frame = CGRectMake(0,0,self.frame.size.width,self.frame.size.height)
self.addSubview(centerView)
}
}
答案 0 :(得分:1)
您应该根据条件设置框架。试试这个:
func orientationChanged()
{
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
print("landscape") // set frame for landscape
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
print("Portrait") // set frame for portrait
}
}
答案 1 :(得分:0)
您甚至没有更改视图的高度和宽度,请将以下代码添加到orientationChanged()
以了解设备的当前方向并调整其大小。
func orientationChanged() {
// Consider using UIScreen.mainScreen().bounds.width and height in CGRect
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
print("landscape")
centerView.frame = // CGRect for landscape
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
print("Portrait")
centerView.frame = //CGRect for portrait
}
}
答案 2 :(得分:0)
您需要调整basicView类的视图,而不仅仅是它的子视图。
func orientationChanged() {
self.frame = CGRectMake(0, 0,556.0,290.0);
}
此外,您需要检查当前设备方向并根据方向设置框架
func orientationChanged() {
if(isLandscape) {}
else {}
}