我正在使用“编程iOS 8”中的以下代码。我有一个带有约束的子视图,其中包含一个简单的文本字段。这个视图有超级视图约束的顶部和底部,我有出口。我也有子视图的出口。这里的目标是当键盘出现时,它会推动这个子视图。我在“let f = self.fr!.frame”一行中收到错误。主题1:EXC_BAD_INSTRUCTION。是否与需要拆开可选项有关?这可能是我的约束问题吗?任何帮助将非常感激。谢谢。
import UIKit
class ViewController: UIViewController {
@IBOutlet var topSpace: NSLayoutConstraint!
@IBOutlet var bottomSpace: NSLayoutConstraint!
@IBOutlet var slidingView: UIView!
var fr: UIView?
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardShow:",
name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardHide:",
name: UIKeyboardWillHideNotification, object: nil)
super.viewDidLoad()
}
func textFieldDidBeginEditing(tf: UITextField) {
self.fr = tf // keep track of the first responder
}
func textFieldShouldReturn(tf: UITextField) -> Bool {
tf.resignFirstResponder()
self.fr = nil
return true
}
func keyboardShow(n:NSNotification) {
let d = n.userInfo!
var r = (d[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
r = self.slidingView.convertRect(r, fromView:nil)
let f = self.fr!.frame
let y : CGFloat =
f.maxY + r.size.height - self.slidingView.bounds.height + 5
if r.origin.y < f.maxY {
self.topSpace.constant = -y
self.bottomSpace.constant = y
self.view.layoutIfNeeded()
}
}
func keyboardHide(n:NSNotification){
self.topSpace.constant = 0
self.bottomSpace.constant = 0
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
如果我没弄错,键盘会在您开始编辑之前显示,因此当您的键盘显示时,您的self.fr仍为零。检查它是否为零。它不应该对可选的展开做任何事情。它只在打开null时失败。