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

标签 swift uibutton

我正在尝试添加一个(角半径为 25.0 的自定义)UIButton 以悬停在我的 View Controller 中的键盘上方。

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

    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 以始终悬停在键盘上方?

谢谢。

最佳答案

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

//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()

关于Swift:以编程方式在键盘上方添加 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577435/

相关文章:

ios8/xcode6.1 : custom font ignored at runtime when set in storyboard

ios - 当 UILabel 动态调整大小时,移动 UIView 中的 UIButton。 iOS系统

swift - 如何在 Xcode 中为 Perfect 检索/生成 PerfectLib.framework 文件?

ios - 与包含它们的字符集相比,只有 2 个表情符号返回不正确的长度

ios - 如何在 Swift 中将按钮添加到 MKPointAnnotation

ios - 移动以编程方式生成的按钮

iphone - 如何将这些左箭头和右箭头添加到我的工具栏?

swift - 点击按钮时更改 UIButton 的图像

ios - Realm swift 线程安全变量

ios - 添加 NSManagedObjects 子类时出错