如何仅在Swift中为我的应用制作自定义键盘? [英] How to make custom keyboard only for my app in Swift?

查看:101
本文介绍了如何仅在Swift中为我的应用制作自定义键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在Swift中为我的应用制作自定义键盘?我不希望人们去设置然后添加键盘.我希望他们能够在我的应用程序上立即使用它.不需要额外的工作.

How to make custom keyboard only for my app in Swift? I do not want people to go to setting and then add keyboard. I want them to be able to use it immediately when they want it on my app. No extra work needed.

如何在Swift中实现这一点?

How to implement this in Swift?

许多链接只谈论在设置中添加新键盘.我不要那个.

Many links only talks about add new keyboard in setting. I don't want that.

我对UI还是很陌生,请给我详细说明.

I'm quite new to UI please give me detail explanation.

推荐答案

用于文本输入的UITextField和UITextView类都具有inputView属性.默认情况下,此属性为nil,但如果为它提供一个视图,则在编辑该文本字段时将弹出该视图,而不是普通键盘.

The UITextField and UITextView classes that you use for text input both have an inputView property. This property is nil by default, but if you provide it with a view, that view will pop up instead of the normal keyboard when editing that text field.

要实现此目的,请创建UIView的子类,以设置您的自定义键盘布局.然后,当您在应用中使用文本字段或文本视图时,必须分别为每个字段设置,如下所示:

To implement this, create a subclass of UIView that sets up your custom keyboard layout. Then, when you use a text field or text view in your app, you have to set it separately for every field, as follows:

let myCustomKeyboard = MyCustomKeyboardView()
myTextField.inputView = myCustomKeyboard

就这样,现在您的文本字段使用您提供的自定义键盘.

That's it, now your text field uses the custom keyboard you provided.

由于您要在应用程序中全局使用键盘,并且必须为每个文本字段或文本视图分别设置键盘,因此该解决方案将导致大量代码重复.由于代码重复被普遍认为是一件坏事,因此,在您的情况下,更好的实现方法是将UITextField或UITextView子类化(显然取决于所使用的那个),并在构造函数中设置键盘:

Since you want to use the keyboard globally in your app, and the keyboard has to be set separately for every text field or text view, this solution would lead to a lot of code duplication. Since code duplication is widely regarded as a bad thing to have, in your case a better implementation would be to subclass UITextField or UITextView (depending on which one you use, obviously), and set the keyboard in the constructor:

class MyCustomKeyboardTextField: UITextField {

    override init() {
        super.init()
        setupCustomKeyboard()
    }

    required init(coder: aCoder) {
        super.init(aCoder)
    }

    override func awakeFromNib() {
        setupCustomKeyboard()
    }

    func setupCustomKeyboard() {
        // Set the custom keyboard
        self.inputView = MyCustomKeyboardView()
    }
}

现在,无论您在哪里使用此子类,都将使用自定义键盘视图.

Now the custom keyboard view will be used wherever you use this subclass.

这篇关于如何仅在Swift中为我的应用制作自定义键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆