t根据用户输入更改UIButton文本

时间:2018-02-04 04:06:27

标签: swift uilabel

我的UINavigationBar上有一个按钮,我使用此代码创建了该按钮:

let inputLabel = UIBarButtonItem(title: userInput, style: .plain,   target: self, action: #selector(inputLabelButtonTapped))

我想根据用户输入的内容制作inputLabel.text。以下是我想象的inputLabelButtonTapped函数,但我无法对其进行编码:

inputLabelButtonTapped() {

// Have a keyboard/numberpad appear on the screen
// Save the what the user types on the screen to a newUserInputVariable
// Make the inputLabel.text = newUserInputVariable

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您似乎与UIBarButtonItemUILabel不匹配。前者是一个可以放在UINavigationControllerUITabBarController中的按钮。后者只显示文字。

通过向ViewController添加UITextFieldUIAlertViewController来实例化输入字段:

var barButtonItemTitle = String()

// create the alert controller
 let ac = UIAlertController(title:"<SomeName>",
                             message: "<SomeMessage>", 
                             preferredStyle: UIAlertControllerStyle.alert)

使用完成处理程序向UIAlertAction添加UIAlertViewController,以便您更新barButtonItemTitle

的属性
let action = UIAlertAction(title: "OK", style: .default) { _ in
//Add a textfield to the alert controller:
 ac.addTextField

当您向UITextField添加UIAlertController时,如果[TextFields]存在,它将显示在// Unwrap the textfield array and the first item there and access the text property. guard let inputText = ac.textFields?.first?.text else {return} 中。

 barButtonText = inputText
}

 // Add action to the controller & present the view.

ac.addAction(action)
present(ac, animated: true)

将barButtonText属性设置为拉出的文本

UIBarButtonItem

使用新值更新barButtonText后,您可以使用该属性创建let barButton = UIBarButtonItem(title: barButtonText, style: .plain, target: nil, action: nil) 的实例并将其放置在任何位置。

TwoViewController

您可以将所有内容包装到分配给视图的func中

相关问题