如何在Swift 2.0中使用完成按钮进行数字键盘操作?

时间:2017-01-10 05:46:36

标签: ios swift2 keyboard

我已尝试使用完成按钮的大量数字键盘,但在SWIFT 2.0中找不到正确的答案。

2 个答案:

答案 0 :(得分:6)

您可以使用工具栏

在键盘上方添加完成按钮
override func viewDidLoad() {
    super.viewDidLoad()
    let tooBar: UIToolbar = UIToolbar()
    tooBar.barStyle = UIBarStyle.BlackTranslucent
    tooBar.items=[
        UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil),
        UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "donePressed")]
    tooBar.sizeToFit()
    yourTextFeild.inputAccessoryView = tooBar
}

func donePressed () {
    yourTextFeild.resignFirstResponder()
}

看起来像这样

enter image description here

答案 1 :(得分:1)

没有工具栏,我通过以下步骤在返回键位置添加了完成按钮,

创建一个自定义的返回按钮,如下所示

public static void setTitleBarBackgroundColor(int color)
{
    if(toolBar != null)
    {
        toolBar.setBackgroundColor(color);
    }
}
...
MyToolBarClass.setTitleBarBackgroundColor(getResources().getColor(android.R.color.transparent));

在viewdidload中,设计它。在这里,我正在设计Next按钮,因为我需要Next而不是Done。

let mobilePadNextButton = UIButton(type: UIButtonType.custom)

添加Keyboad通知

mobilePadNextButton.setTitle("Next", for: UIControlState())//Set Done here
mobilePadNextButton.setTitleColor(UIColor.black, for: UIControlState())
mobilePadNextButton.frame = CGRect(x: 0, y: 163, width: 106, height: 53)
mobilePadNextButton.adjustsImageWhenHighlighted = false
mobilePadNextButton.addTarget(self, action: #selector(self.mobilePadNextAction(_:)), for: UIControlEvents.touchUpInside)

在这里,您可以执行完成的操作

func textFieldDidBeginEditing(_ textField: UITextField) {
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}


func keyboardWillShow(notification:NSNotification){

    if mobileNoTxtFld.isFirstResponder
    {
        DispatchQueue.main.async { () -> Void in
            self.mobilePadNextButton.isHidden = false
            let keyBoardWindow = UIApplication.shared.windows.last
            self.mobilePadNextButton.frame = CGRect(x: 0, y: (keyBoardWindow?.frame.size.height)!-53, width: 106, height: 53)
            keyBoardWindow?.addSubview(self.mobilePadNextButton)
            keyBoardWindow?.bringSubview(toFront: self.mobilePadNextButton)

            UIView.animate(withDuration: (((notification.userInfo! as NSDictionary).object(forKey: UIKeyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
                self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
            }, completion: { (complete) -> Void in
                print("Complete")
            })
        }
    }
    else
    {
        self.mobilePadNextButton.isHidden = true
    }

}

UI将如下所示,

enter image description here

我提到了Git Code