(Xcode 8 Swift 3)。使用自定义键盘扩展与特定文本字段

时间:2016-09-24 15:02:51

标签: ios swift xcode keyboard

enter image description here

由于标准数字键盘键盘有“空”键,但没有“+/-”键,我决定创建自己的键盘扩展键。我做到了 enter image description here

但是我不知道如何使用常用键盘将其与特定文本字段链接(并调用),而其他文本字段则使用。 有没有机会像我自己的自定义键盘一样应用自定义keyboardType?

2 个答案:

答案 0 :(得分:1)

我找到了基于类似问题的解决方案:How to input text using the buttons of an in-app custom keyboard

import UIKit

protocol KeyboardDelegate: class {
    func keyWasTapped(text: String)
}

class KeyboardView: UIView {

    // This variable will be set as the view controller so that
    // the keyboard can send messages to the view controller.
    weak var delegate: KeyboardDelegate?


    // MARK:- keyboard initialization
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeSubviews()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeSubviews()
    }

    func initializeSubviews() {
        let xibFileName = "KeyboardView" // xib extention not included
        let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)?[0] as! UIView
        self.addSubview(view)
        view.frame = self.bounds
    }

    // MARK:- Button actions from .xib file    
    @IBAction func keyTapped(_ sender: UIButton) {
        // When a button is tapped, send that information to the
        // delegate (ie, the view controller)
        self.delegate?.keyWasTapped(text: sender.titleLabel!.text!) // could alternatively send a tag value
    }

}

/ *出错时:"无法在捆绑中加载NIB"  Could not load NIB in bundle 访问文件检查器中的.xib文件的属性,属性" Target Membership"选择框上的音高,然后您的xib文件与目标链接  * /

在主ViewController.swift

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, KeyboardDelegate {

    @IBOutlet weak var text1: UITextField!
    @IBOutlet weak var text2: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // initialize custom keyboard
        let keyboardView = KeyboardView(frame: CGRect(x: 0, y: 0, width: 375, height: 165))
        keyboardView.delegate = self // the view controller will be notified by the keyboard whenever a key is tapped

        // replace system keyboard with custom keyboard
        text1.inputView = keyboardView //accessoryView
        text1.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // required method for keyboard delegate protocol
    func keyWasTapped(text character: String) {

        if Int(character) != nil{
            text1.insertText(character)
        }

        if character == "⌫" {
            if !(text1.text?.isEmpty)! {
                let beforeText = text1.text!
                let truncated = beforeText.substring(to: beforeText.index(before: beforeText.endIndex))
                text1.text = truncated

            }
        }

        if character == "±" {
            let beforeText = text1.text!
            if var number = Int(beforeText) {
                number = -number
                text1.text = "\(number)"
            }
        }


    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        /*
        if (textField == self.text1) {
            //textField.inputView = keyboardView
        }
        */
    }

}

enter image description here

答案 1 :(得分:0)

我为公制/英制系统编码了一个计算器。为此,我也编写了自己的键盘。

enter image description here

我已将键盘设置为堆叠视图中的UIButtons

enter image description here

由于我刚刚升级到Xcode 8并且该项目仍然在Swift 2.2中,因此Xcode的按钮似乎未知。

enter image description here

然后我设置了一个UITextField并使用我的按钮填充了它的text属性。这是我键盘上按钮1的功能。

@IBOutlet weak var inputField: UITextField!
var numberStr:String = "0"
inputField.text = numberStr

@IBAction func oneKeyboardAction(sender: AnyObject) {
    if numberStr == "0" {
        numberStr = String(numberStr.characters.dropLast())
    }
    let newStr:String = numberStr + String("1")
    numberStr = newStr
    let dotToCommaString = newStr.stringByReplacingOccurrencesOfString(".", withString: ",")
    inputField.text = dotToCommaString
}

此外,我已停用与TextField的用户互动,因此“原始键盘”将不会显示。

修改

如评论部分所述,让我的答案更符合您的需求。您可以将我的自定义键盘设置为UIView,与Interface Builder中的UIViewController重叠。将其设置为MyKeyboardView.hidden = true内的viewDidLoad()

然后你有TextField,你希望自定义键盘可见而不是系统键:

func textFieldDidBeginEditing(_ textField: UITextField) {
    if (textField == self.yourDesiredTextField) { //the one where you want to use the custom keyboard 
        MyKeyboardView.hidden = false
    }
}

然后你添加一个这样的手势识别器:

override func viewDidLoad() {
        super.viewDidLoad()

        MyKeyboardView.hidden = true


        let tap = UITapGestureRecognizer(target: self, action: #selector(gesture))
        tap.numberOfTapsRequired = 1
        view.addGestureRecognizer(tap)
}

func gesture() {

        UIView.animateWithDuration(0.2) {
            self.MyKeyboardView.hidden = true
        }

}

为了让它更加流畅,我在隐藏键盘时添加了animateWithDuration