Swift:在 iOS 中显示的键盘顶部创建边框或细线

Swift: Creating a border or a thin line on top of the displaying Keyboard in iOS

如主题所述,我尝试在我的 UIKeyboard 外观上创建一条小线。原因是,如果我在白色背景下弹出白色键盘,它看起来很糟糕。

一个想法是创建一条 1px 的细线并将其放在底部,隐藏它并在显示键盘时显示它并将其与自动布局对齐。这个思路的缺点是每个视图都要做。

谢谢你的想法。

每个 UITextFieldUITextView 都有一个 inputAccessoryView 属性(继承自 UIResponder 超类)。当其中一个视图成为第一响应者并且系统显示屏幕键盘时,系统会自动在键盘顶部显示第一响应者的 inputAccessoryView。例如in this answer,带有左右箭头和“完成”按钮的深色条是inputAccessoryView

因此,在键盘顶部获得一条细线的最简单方法可能是创建一个点高视图并将其设置为文本字段或文本视图的 inputAccessoryView。将附件视图的背景颜色设置为深色。

正如 Rob 已经写的那样,AccessoryView 是正确且最流畅的解决方案,因为 Apple 以正确的方式解决了所有动画、显示等问题,所以不用担心其他任何事情。

我把它作为扩展解决了。我希望它在底部显示一个小的分隔线,所以我有一个封闭的数字键盘:

Swift 2.0:

extension UITextField {

override public func becomeFirstResponder() -> Bool {
    self.addSeparatorInputAccessoryIfNumericKeyboardOnPhone()
    return super.becomeFirstResponder()
}

func addSeparatorInputAccessoryIfNumericKeyboardOnPhone() {
    guard self.keyboardType == .NumberPad else {
        return
    }

    guard UIDevice.currentDevice().userInterfaceIdiom == .Phone else {
        return
    }

    let view = UIView(frame: CGRectMake(0, 0, 0, 1 / UIScreen.mainScreen().scale))
    view.backgroundColor = UIColor.lightGrayColor()
    self.inputAccessoryView = view
}

}

最简单的方法是在 textFiled 成为第一响应者并且系统显示屏幕键盘时为它添加一个 inpustAccessoryView。

试试这个: Swift 3:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {   

        let separatorView = UIView(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1))
        separatorView.backgroundColor = UIColor.lightGray
        textField.inputAccessoryView = separatorView

    return true
}