我正在尝试让我的keybordview打开方向更改 - 我的.xib中的视图与@IBOutlet连接然后我用viewDidLoad()内的loadInterface()调用它们我希望我的调用viewDidLoad会更新界面,但我认为它的工作方式并不像我想的那样 - 它不会破坏任何东西,但它也不起作用(尽管如此,我从上周开始取得了大量进展。)。
我感觉这是方向改变的事情......
import UIKit
class KeyboardViewController: UIInputViewController {
@IBOutlet var keyboardViewPortrait: UIView!
@IBOutlet var keyboardViewLandscape: UIView!
func loadInterface(){
var keyboardNib = UINib(nibName: "keyboardView", bundle: nil)
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
if self.interfaceOrientation.isLandscape {
self.keyboardViewLandscape = keyboardNib.instantiateWithOwner(self, options: nil)[0] as UIView
view.addSubview(self.keyboardViewLandscape)
view.backgroundColor = self.keyboardViewLandscape.backgroundColor
}
else if self.interfaceOrientation.isPortrait {
self.keyboardViewPortrait = keyboardNib.instantiateWithOwner(self, options: nil)[0] as UIView
view.addSubview(self.keyboardViewPortrait)
view.backgroundColor = self.keyboardViewPortrait.backgroundColor
}
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
}
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
loadInterface()
...
}
}
*更新
我认为rdelmar让我走上正确的道路,但仍然缺少一些东西。
谢谢!
答案 0 :(得分:1)
问题是你为self.keyboardViewLandscape和self.keyboardViewPortrait分配了相同的视图(在两种情况下都是你从keyboardNib.instantiateWithOwner获得的视图(self,options:nil)[0])。其中一个属性应该分配给索引1处的对象。另外,使用new方法处理旋转可能更好,viewWillTransitionToSize:withTransitionCoordinator:。您还需要在添加新视图时删除上一个视图。
class ViewController: UIViewController {
var keyboardViewPortrait: UIView!
var keyboardViewLandscape: UIView!
var keyboardNib = UINib(nibName: "keyboardView", bundle: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.keyboardViewPortrait = keyboardNib.instantiateWithOwner(self, options: nil)[0] as UIView
view.addSubview(self.keyboardViewPortrait)
view.backgroundColor = self.keyboardViewPortrait.backgroundColor
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator){
if size.width > size.height {
self.keyboardViewPortrait.removeFromSuperview()
self.keyboardViewLandscape = keyboardNib.instantiateWithOwner(self, options: nil)[1] as UIView
view.addSubview(self.keyboardViewLandscape)
view.backgroundColor = self.keyboardViewLandscape.backgroundColor
}
else {
self.keyboardViewLandscape.removeFromSuperview()
self.keyboardViewPortrait = keyboardNib.instantiateWithOwner(self, options: nil)[0] as UIView
view.addSubview(self.keyboardViewPortrait)
view.backgroundColor = self.keyboardViewPortrait.backgroundColor
}
}
}