带有uibar的Textfileld,用于关闭键盘垫

时间:2018-09-07 08:56:55

标签: ios swift xcode textfield

我创建了一个申请表,在某些字段中我使用数字键盘。缺少关闭按钮,我进入了包含关闭按钮的uibar。

我当前为每个字段创建一个uibar,因为我必须指定目标。只能创建一个具有多个目标的uibar吗?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow(); // in Activity's onCreate() for instance
            w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

等等等

image

2 个答案:

答案 0 :(得分:0)

var keyConstTextField : UInt = 0
extension UIToolbar {

func addToolBar(_ vc : UIViewController,textFiled : UITextField) -> UIToolbar {

    let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))

    toolBar.isTranslucent = true
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
    button.setTitle("DONE", for: .normal)
    button.titleLabel?.font = UIFont(name: "OpenSans-Semibold", size: 17.0)
    button.addTarget(vc, action: #selector(UIViewController.toolBarDoneButtonPressed(_:)), for: .touchUpInside)
    button.backgroundColor = .white
    button.titleLabel?.textColor = UIColor.black

    let done = UIBarButtonItem(customView: button)
    let fixSpace1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let fixSpace2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)

    objc_setAssociatedObject(button, &keyConstTextField, textFiled, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)


    toolBar.setItems([fixSpace1,done,fixSpace2], animated: false)
    return toolBar
}

}

extension UIViewController {

//TODO:- To get textfield on specific in below override. You have to fetch from OBJC using keyConstTextField key.
@objc func toolBarDoneButtonPressed(_ sender : UIButton) {

    self.view.endEditing(true)

    if let textField = objc_getAssociatedObject(sender, &keyConstTextField) as? UITextField {
        print(textField.text ?? "Not Found....")
    }
}
}
  

使用上述方法,您可以使用UIViewController扩展名定义常用操作。

答案 1 :(得分:0)

        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true
        toolBar.sizeToFit()
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(doneClickOk))
        toolBar.setItems([doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        yourTextField.inputAccessoryView = toolBar
        yourOthersTextfields.inputAccessoryView = toolBar


**Than call selector method** 

@objc func doneClickOk(){
    view.endEditing(true)
}