iOS 从 XIB 文件加载时 Swift 中的键盘太宽太高

iOS Keyboard in Swift is too wide and tall when loading from XIB file

我正在使用 Swift(XCode 6 和 iOS 8.3 SDK)构建键盘,当我加载 xib 时,键盘大约 1000 像素太宽太高.我已经在自由形式的 xib 文件中将所有键放入 UIView 并将 UIViews 约束设置为超级视图顶部、底部、左侧和右侧。

如您所见,结果很烦人。这是我的代码:

import UIKit

class KeyboardViewController: UIInputViewController {

var BlurBoardView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadInterface()
}

func loadInterface() {
    //load the nib file
    var blurboardNib = UINib(nibName: "BlurBoardView", bundle: nil)
    // initiate the view
    BlurBoardView = blurboardNib.instantiateWithOwner(self, options: nil)[0] as! UIView
    // add the interface to the main view
    view.addSubview(BlurBoardView)
    // copy the background color
    view.backgroundColor = BlurBoardView.backgroundColor

    let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
    blur.frame = view.frame
    view.addSubview(blur)
}

@IBAction func didTapButton(sender: AnyObject?) {

    let button = sender as! UIButton
    let title = button.titleForState(.Normal)
    var proxy = textDocumentProxy as! UITextDocumentProxy

    switch title as String!{
        case "<" :
            proxy.deleteBackward()
        case "RETURN" :
            proxy.insertText("\n")
        case " " :
            proxy.insertText(" ")
        case "CHG" :
            self.advanceToNextInputMode()
        default :
            proxy.insertText(title!)
    }
}

/*
override func textWillChange(textInput: UITextInput) {
    // The app is about to change the document's contents. Perform any preparation here.
}

override func textDidChange(textInput: UITextInput) {
    // The app has just changed the document's contents, the document context has been updated.

    var textColor: UIColor
    var proxy = self.textDocumentProxy as! UITextDocumentProxy
    if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
        textColor = UIColor.whiteColor()
    } else {
        textColor = UIColor.blackColor()
    }
    //self.nextKeyboardButton.setTitleColor(textColor, forState: .Normal)
}
*/
}

预编译 xib 中的键盘如下所示:

您还可以看到(键的)父视图约束。

我主要是一名 Objective-C 开发人员,所以代码很有意义,但由于 Swift,问题可能只是一个巨大的 SBE,如果它简单得可笑,我们深表歉意;)

编辑:P 键有一个约束,将它与左侧超级视图绑定 14 个像素,向右(与 O 键)绑定 0 个像素,这就是我知道它太宽的原因。键盘底部约束是到超级视图的底部。

看起来您正在使用自动布局,并且您没有在视图和 BlurBoardView 之间设置约束。

调用 ViewDidLoad 时,视图没有正确的框架。仅在调用 viewDidLayoutSubviews 时。

因此,在 ViewDidLoad 中设置视图和 BlurBoardView 之间的约束。或者把BlurBoardView.frame = 你想要的框架放在viewDidLayoutSubview中。

blurView 也一样