Swift:以编程方式在键盘上方添加UIButton

时间:2016-07-25 21:07:31

标签: swift uibutton

我试图添加一个(角半径为25.0的自定义)UIButton悬停在视图控制器的键盘上方。

我已尝试通过使用以下代码将此按钮添加到工具栏来自行完成此操作,但是,我不是在寻找工具栏:

    let toolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
    toolbar.barStyle = UIBarStyle.Default
    loginButton.titleLabel?.textColor = UIColor.whiteColor()
    loginButton.backgroundColor = UIColor.redColor()
    loginButton.titleLabel?.text = "Sign Up"
    loginButton.addTarget(self, action: #selector(signUp), forControlEvents: .TouchUpInside)
    let customButton = UIBarButtonItem(customView: loginButton)
    toolbar.items = [customButton]
    toolbar.sizeToFit()
    //...
    //When credentials are valid, show/enable button...
    usernameEmailField.inputAccessoryView = toolbar

如何添加UIButton以始终悬停在键盘上方?

谢谢。

1 个答案:

答案 0 :(得分:0)

这个对我有用。请试试这个

//create toolbar object
        let doneToolBar: UIToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 44))
        doneToolBar.barStyle = UIBarStyle.BlackTranslucent
        //add barbuttonitems to toolbar
        let flexsibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) // flexible space to add left end side
        let doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(UITextField.didPressDoneButton))
        doneToolBar.items = [flexsibleSpace,doneButton]
        //assing toolbar as inputAccessoryView
        textField.inputAccessoryView = doneToolBar
        doneToolBar.sizeToFit()
相关问题