【问题标题】:How to add a minus sign to the .DecimalPad iOS keyboard?如何在 .DecimalPad iOS 键盘上添加减号?
【发布时间】:2015-03-21 23:50:54
【问题描述】:

如何向 .DecimalPad 类型的 iOS 键盘添加减号,就像下面链接中的应用程序一样?如果我错了,请纠正我,但这对我来说似乎不是自定义键盘,它看起来像是 Apple 对我的默认十进制键盘......

Decimal keypad with a minus sign

【问题讨论】:

标签: ios swift xcode button keyboard


【解决方案1】:

要向键盘添加一些键,请打开 KeyboardViewController.swift 并进行以下更改。

在 viewDidLoad() 中,在函数底部的下一个键盘按钮代码之后添加以下内容。

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)

接下来添加下面的函数,它将创建带有传递给它的字符串标题的按钮。

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
}

此函数遍历字符串数组并创建具有相应标题的按钮。它还为每个按钮添加了一个目标,以便在点击它时调用函数 keyPressed()。接下来添加这个函数。

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

在这里,您可以获取点击按钮的标题,并通过 textDocumentProperty 将其插入当前文本输入对象的插入点。这是一个符合 UITextDocumentProxy 协议的对象,它充当键盘和调用它的文本输入对象之间的代理。

接下来我们添加 addConstraints() 方法,该方法将为按钮和包含视图添加约束。

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])
        }
    }

运行应用程序,您应该会看到一个类似的键盘,如下所示

如您所见,以编程方式添加视图需要您在代码中设置约束,如果您的键盘 UI 很复杂并且有很多键,这可能会变得复杂且难以调试。接下来我们将看看如何使用 Interface Builder 创建按钮。

通过导航到文件 > 新建 > 文件 > iOS > 用户界面 > 视图来创建一个 nib 文件。将其命名为 KeyboardView 并确保它位于 AC 键盘目标之下。

选择 nib 的视图,在 Attributes Inspector 中,将其 Size 设置为 Freeform 并将 Status Bar 设置为 None。然后转到 Size Inspector 并将其宽度设置为 320,高度设置为 220。

在 KeyboardViewController.swift 中,在调用 super.viewDidLoad() 之后在 viewDidLoad() 中添加以下内容。这会将 nib 文件设置为视图控制器的视图。

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

为笔尖的主视图添加一个视图。单击 Interface Builder 界面底部的 Pin 菜单,并为其设置以下约束 - 高度为 40,尾随空间为 0,前导空间为 0,顶部空间为 42。确保未选中约束到边距。

add_constraints

在视图中添加一个按钮。将文本颜色设置为深灰色并更改标题。现在是约束。

使用每个按钮,选择对齐菜单并选择容器中的垂直居中。

alignment auto layout

选择“-”按钮并在 Superview 中为 5 添加一个前导空格。

选择 '-' 并在 Size Inspector 中,确保它的 Leading Space to S ie 设置为常数 5。

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

运行应用程序,您应该会看到刚刚添加的键设置在您在代码中添加的键下方。

interface_builder_ui

要为按键创建出口和操作,请从文档大纲中选择文件的所有者,然后在身份检查器中,将类设置为 KeyboardViewController。然后,您可以像通常在情节提要文件中所做的那样,通过从控件拖动控件到视图控制器类来创建动作和出口。 (您将在下面的示例中看到更多内容)。

现在我们已经了解了如何使用 nib 文件以编程方式创建键盘的 UI,让我们为其添加一些功能。为此,我有一个我们将使用的入门项目。该项目是一个简单的键盘,我们将添加一些功能。如下所示。你应该注意到,为了简单起见,我没有为所有尺寸等级设计,所以虽然它在 iPhone 5S 上看起来不错,但在更大的屏幕上看起来不太一样。你可以在这里下载代码。另请注意,键盘的名称是 Appcoda 键盘,而不是我们之前使用的 AC 键盘。

keyboard_starter

我已经设置了我们需要的动作和出口,但还没有为它们编写代码(下一个键盘键除外)。

首先,您会注意到 Next Keyboard 键已替换为名为 KB 的键。其动作方法可以在视图控制器文件中看到,如下所示。

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

我们首先要为带有字母和符号的键设置操作,即您点击的任何键并将其标题视为键入的文本。我为所有这些键创建了一个名为 keyPressed() 的操作方法。如图修改这个方法。

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

这与我们之前的类似。按钮的标题通过 textDocumentProperty 插入到当前文本输入对象的插入点。我们输入的所有字母都将使用大写字母,但我们会尽快解决这个问题。接下来修改以下函数,分别设置退格(BS)、空格(SPACE)和返回(RTN)键的动作。

@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")
}

运行应用程序并测试密钥。

在视图文件中,您会注意到标记为 Char Set 1 和 Char Set 2 的两个视图。它们位于同一行,一个在另一个之上。在 viewDidLoad() 中,第二个视图被隐藏了。修改 charSetPressed() 函数,如图所示,当用户按下标记为 1/2 的键时,键的文本将变为 2/2,并且一组新的字符将出现在键盘的第一行。

@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)
    }
}

字符集 如果您查看系统键盘,通常会有一个指示,在您轻按某个键时以简短动画的形式出现。我们应该添加某种反馈,以便用户知道他们点击了正确的键。在 keyPressed() 方法的末尾添加以下内容。

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

这会使按键在轻按时短暂放大,然后再恢复其原始大小。

最后我们将实现 Capslock 键(CL)。修改 capsLockPressed() 函数如下。

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

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

Reference

【讨论】:

  • 代码需要稍作调整,它只是根据参考调整样本
  • 好的,谢谢;它看起来并不难,我会看看我能做什么。感谢您也使用 Swift ;)
  • @RachelGallen 我可以在 React Native 中实现这个吗?
猜你喜欢
  • 2021-09-04
  • 2023-04-04
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 2012-11-19
  • 2021-07-20
  • 1970-01-01
相关资源
最近更新 更多