如何将减号添加到.DecimalPad的iOS键盘? [英] How to add a minus sign to the .DecimalPad iOS keyboard?

查看:765
本文介绍了如何将减号添加到.DecimalPad的iOS键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加一个减号.DecimalPad类型的iOS键盘就像从下面的链接应用程序?纠正我,如果我错了,但是这似乎并不像一个自定义的键盘对我来说,它看起来像苹果的默认小数键盘给我...

How can I add a minus sign to the .DecimalPad type iOS keyboard like the app from the link below? Correct me if I'm wrong, but that doesn't seem like a custom keyboard to me, it looks like the default decimal keypad from Apple to me...

用减号十进制键盘

推荐答案

要某些键添加到键盘,开放KeyboardViewController.swift并进行以下修改。

To add some keys to the keyboard, open KeyboardViewController.swift and make the following changes.

在viewDidLoad中()的code下一个键盘按键之后添加以下在函数的底部。

In viewDidLoad() add the following at the bottom of the function right after the code for the next keyboard button.

let buttonTitles = ["-"]
var buttons = createButtons(buttonTitles)
var topRow = UIView(frame: CGRectMake(0, 0, 320, 40))

for button in buttons {
    topRow.addSubview(button)
}

self.view.addSubview(topRow)

addConstraints(buttons, containingView: topRow)

接下来,添加下面这将创造与传递给它的字符串的标题按钮的功能。

Next add the function below which will create buttons with titles of the strings passed into it.

func createButtons(titles: [String]) -> [UIButton] {

    var buttons = [UIButton]()

    for title in titles {
        let button = UIButton.buttonWithType(.System) as UIButton
        button.setTitle(title, forState: .Normal)
        button.setTranslatesAutoresizingMaskIntoConstraints(false)
        button.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        button.addTarget(self, action: "keyPressed:", forControlEvents: .TouchUpInside)
        buttons.append(button)
    }

    return buttons
}

此功能通过一个字符串数组进行迭代,并创建相应的标题按钮。它还增加了一个目标到每个按钮,从而当它被窃听,功能键pressed()将被调用。接下来,添加这个功能。

This function iterates through an array of Strings and creates buttons with the respective titles. It also adds a target to each button so that when it is tapped, the function keyPressed() will be called. Next add this function.

func keyPressed(sender: AnyObject?) {
    let button = sender as UIButton
    let title = button.titleForState(.Normal)
    (textDocumentProxy as UIKeyInput).insertText(title!)
}

在这里,你得到挖掘按钮的名称,并在通过textDocumentProperty当前文本输入对象的插入点插入。这是符合UITextDocumentProxy协议的对象,其作为键盘和召唤它文本输入物体之间的代理。

Here you get the title of the tapped button and insert it at the insertion point of the current text input object via the textDocumentProperty. This is an object conforming to the UITextDocumentProxy protocol, which acts as a proxy between the keyboard and the text input object that summoned it.

接下来我们添加addConstraints()方法,将约束添加到按钮和containingView。

Next we add the addConstraints() method which will add constraints to the buttons and the containingView.

func addConstraints(buttons: [UIButton], containingView: UIView){

        for (index, button) in enumerate(buttons) {

            var topConstraint = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: containingView, attribute: .Top, multiplier: 1.0, constant: 1)

            var bottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: containingView, attribute: .Bottom, multiplier: 1.0, constant: -1)

            var leftConstraint : NSLayoutConstraint!

            if index == 0 {

                leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: containingView, attribute: .Left, multiplier: 1.0, constant: 1)

            }else{

                leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: buttons[index-1], attribute: .Right, multiplier: 1.0, constant: 1)

                var widthConstraint = NSLayoutConstraint(item: buttons[0], attribute: .Width, relatedBy: .Equal, toItem: button, attribute: .Width, multiplier: 1.0, constant: 0)

                containingView.addConstraint(widthConstraint)
            }

            var rightConstraint : NSLayoutConstraint!

            if index == buttons.count - 1 {

                rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: containingView, attribute: .Right, multiplier: 1.0, constant: -1)

            }else{

                rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: buttons[index+1], attribute: .Left, multiplier: 1.0, constant: -1)
            }

            containingView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint])
        }
    }

运行应用程序,你将看到类似的键盘如下图所示。

Run the app and you should see a similar keyboard as shown below

正如你所看到的,添加视图编程需要您设置在code约束和如果你的键盘的用户界面是复杂的,有许多按键,这可能很复杂,很难调试。接下来我们就来看看用接口生成器来创建按钮。

As you can see, adding views programmatically requires you to set up constraints in code and if your keyboard’s UI is complicated and has many keys, this can get complicated and hard to debug. Next we will look at using the Interface Builder to create buttons.

导航到File> New>文件>的iOS>用户界面>视图中创建一个笔尖文件。将其命名为KeyboardView,并确保它是AC键盘目标之下。

Create a nib file by navigating to File > New > File > iOS > User Interface > View. Name it KeyboardView and make sure it is under the AC Keyboard target.

选择笔尖的观点,并在属性检查器,设置其大小为自由曲面和状态栏为无。然后去尺寸检查其宽度设置为320和高度为220。

Select the nib’s view and in the Attributes Inspector, set its Size as Freeform and Status Bar to None. Then go to the Size Inspector and set its width to 320 and height to 220.

在KeyboardViewController.swift调用super.viewDidLoad后加入viewDidLoad中()以下的()。这台笔尖文件视图控制器的看法。

In KeyboardViewController.swift add the following in viewDidLoad() after the call to super.viewDidLoad(). This sets the nib file as the view of the view controller.

let nib = UINib(nibName: "KeyboardView", bundle: nil)
let objects = nib.instantiateWithOwner(self, options: nil)
view = objects[0] as UIView;

添加以笔尖的主视图。点击PIN菜单上的界面生成器界面的底部,并给它下面的约束 - 40高度,尾随的0空间,前顶空间的0空间和42制作的容器一定约束保证金不作检查。

Add a view to the nib’s main view. Click on the Pin menu at the bottom of the Interface Builder interface and give it the following constraints – Height of 40, Trailing space of 0, Leading space of 0 and Top space to container of 42. Make sure Constrain to margin is not checked.

add_constraints

添加一个按钮到视图。设置文本颜色为深灰色,并更改标题。现在的限制。

Add a button to the view. Set the text color to Dark Gray and change the title. Now for the constraints.

对于每个按钮,选择菜单对齐和集装箱选择垂直中心。

With each button, select the Align menu and select Vertical Center in Container.

alignment auto layout

选择了 - 按钮,添加一个空格,SuperView已经5.

Select the '-' button and add a Leading space to Superview for 5.

选择 - 和在大小检查,确保其领先的空间给S IE设置为5恒定

Select '-' and in the Size Inspector, make sure that its Leading Space to S ie set to a constant of 5.

选择主视图,然后编辑>解决自动布局问题>所有视图>更新框架。

Select the main view then Editor > Resolve Auto Layout Issues > All Views > Update Frames.

运行应用程序,你应该看到您刚才添加设置下面你在code添加的那些按键。

Run the application and you should see the keys you just added set up below the ones you added in code.

interface_builder_ui

要创建出口和动作的钥匙,从文档大纲中选择文件的所有者,那么在Identity Inspector中,将类KeyboardViewController。然后,您可以创建操作和网点就像你通常通过从控​​制到视图控制器类控制拖做故事板的文件。 (你会看到更多这样在下面的例子)。

To create outlets and actions for the keys, select the File’s Owner from the Document Outline, then in the Identity Inspector, set the class as KeyboardViewController. You can then create actions and outlets like you usually do in storyboard files by Control-dragging from a control to the view controller class. (You’ll see more of this in the example that follows).

现在,我们已经看到了如何编程,用笔尖文件中创建一个键盘的用户界面,让我们添加一些功能吧。对于这一点,我有我们将使用一个启动项目。该项目是一个简单的键盘,我们将添加一些功能的。它如下所示。你应该注意到,以保持它的简单,我并没有为所有规模类设计,这样,虽然看起来在iPhone 5S不错,它不寻求更大的屏幕完全一样。你可以在这里下载code。还要注意的是键盘上的名字是Appcoda键盘,而不是AC键盘我们前面了。

Now that we have seen how to create a keyboard’s UI programmatically and with a nib file, let us add some functionality to it. For this, I have a starter project that we will be using. The project is a of a simple keyboard that we will add some functionality to. It is shown below. You should note that to keep it simple, I didn’t design for all size classes so, while it looks nice on the iPhone 5S, it doesn’t look quite the same for bigger screens. You can download the code here. Also note that the keyboard’s name is Appcoda Keyboard and not the AC Keyboard we had earlier.

keyboard_starter

keyboard_starter

我已经设置了我们所需要的行动和网点,但不写他们的code(除下一页键盘键)。

I have already set up the actions and outlets we’ll require, but haven’t written the code for them (except for the Next Keyboard key).

首先,你会发现,下一步键盘上的键已被替换名为KB的关键。这种操作方法可以看出它的视图控制器文件,如下所示。

First, you’ll notice that the Next Keyboard key has been replaced with a key titled KB. The action method for this can be seen it the view controller file as shown below.

@IBAction func nextKeyboardPressed(button: UIButton) {
    advanceToNextInputMode()
}

我们首先要建立的操作与字母和符号,即点击并看到它的标题作为键入的文本任意键的键。我创建了所有这些钥匙叫键pressed的操作方法()。修改这个方法,如图所示。

We are first going to set up the actions for keys with letters and symbols i.e. any key you tap and see its title as the typed text. I created an action method for all these keys called keyPressed(). Modify this method as shown.

@IBAction func keyPressed(button: UIButton) {
    var string = button.titleLabel!.text
    (textDocumentProxy as UIKeyInput).insertText("\(string!)")
}

这是类似于我们以前。按钮的标题被​​插入在通过textDocumentProperty当前文本输入物体的插入点。我们所键入的字母将是大写的,但我们会尽快解决这个问题。下一步修改以下功能分别设立退格(BS),空间(SPACE)行动,重新回到(RTN)键。

This is similar to what we had before. The title of the button is inserted at the insertion point of the current text input object via the textDocumentProperty. All the letters we type will be in Caps, but we will fix this shortly. Next modify the following functions to set up actions for the backspace(BS), space(SPACE) and return(RTN) keys respectively.

@IBAction func backSpacePressed(button: UIButton) {
    (textDocumentProxy as UIKeyInput).deleteBackward()
}

@IBAction func spacePressed(button: UIButton) {
    (textDocumentProxy as UIKeyInput).insertText(" ")
}

@IBAction func returnPressed(button: UIButton) {
    (textDocumentProxy as UIKeyInput).insertText("\n")
}

运行应用程序和测试键。

Run the app and test the keys.

在视图文件,你会发现标有字符集1和字符集2。这些都在同一行与一个在另一个上面两种观点。在viewDidLoad中()第二种观点是隐藏的。修改如图所示,这样的字符集pressed()函数,当用户presses标记1/2键,该键的文字将变为2/2和一套新的人物都会出现的第一行键盘。

In the view file, you will notice two views labelled Char Set 1 and Char Set 2. These are on the same row with one on top of the other. In viewDidLoad() the second view is hidden. Modify the charSetPressed() function as shown so that when the user presses the key labelled 1/2, the key’s text will change to 2/2 and a new set of characters will appear on the first row of the keyboard.

@IBAction func charSetPressed(button: UIButton) {
    if button.titleLabel!.text == "1/2" {
        charSet1.hidden = true
        charSet2.hidden = false
        button.setTitle("2/2", forState: .Normal)
    } else if button.titleLabel!.text == "2/2" {
        charSet1.hidden = false
        charSet2.hidden = true
        button.setTitle("1/2", forState: .Normal)
    }
}

字符集
如果你看一下系统键盘,通常有一个指示中,当你点击一个键一个简短的动画的形式。这样用户就知道他们挖右键我们应该添加某种反馈。添加如下在键pressed()方法结束

charset If you look at the system keyboard, there is usually an indication, in the form of a brief animation when you tap a key. We should add some sort of feedback so the user knows that they tapped the right key. Add the following at the end of the keyPressed() method.

UIView.animateWithDuration(0.2, animations: {
        button.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2.0, 2.0)
        }, completion: {(_) -> Void in
            button.transform =
                CGAffineTransformScale(CGAffineTransformIdentity, 1, 1)
    })

这使得一个关键规模,短时间的时候才回到原来的大小挖。

This makes a key scale up briefly when tapped before going back to its original size.

最后,我们将实现大写锁定键(CL)。修改CAPSLOCK pressed()函数如下:

Lastly we’ll implement the Capslock key(CL). Modify the capsLockPressed() function as follows.

@IBAction func capsLockPressed(button: UIButton) {
    capsLockOn = !capsLockOn

    changeCaps(row1)
    changeCaps(row2)
    changeCaps(row3)
    changeCaps(row4)
}

参考

这篇关于如何将减号添加到.DecimalPad的iOS键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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