所以我知道这可能是一件容易的事情,但我开始使用swift进行macOS和快速开发。我想制作一个简单的应用程序,询问一个名称,然后说“你好,名字”。在macOS开发中,一种方法是这样做:
@IBOutlet weak var nameField: NSTextField!
.
// More code here
.
@IBAction func helloButton(_ sender: Any) {
var name = nameField.stringValue
if name.isEmpty{
name = "World"
}
let greeting = "Hello, \(name)"
helloLabel.stringValue = greeting
}
无论如何要为iOS做类似的事情吗?我尝试为iOS做这个,但它不适合我。 “nameField.stringValue”不存在。任何帮助,将不胜感激。
@IBOutlet weak var nameField: UITextField!
.
// More code here
.
@IBAction func helloButton(_ sender: Any) {
var name = nameField.text!
if name.isEmpty {
name = "World"
}
let greeting = "Hello, \(name)"
helloLabel.text = greeting
}
我想这可能对你有帮助 -
import UIKit
class ViewController: UIViewController {
//created a string variable
var name: String = ""
//our label to display input
@IBOutlet weak var labelName: UILabel!
//this is the text field we created
@IBOutlet weak var textFieldName: UITextField!
@IBAction func buttonClick(sender: UIButton) {
//getting input from Text Field
name = textFieldName.text!
//Displaying input text into label
labelName.text = "Hello \(name)"
}
}
这是输出 -
参考 - https://www.simplifiedios.net/xcode-text-field-tutorial-ios-using-swift/
谢谢。
你可以做这样的事情。
@IBAction func helloButton(_ sender: Any) {
let name = txtSearch.text
if !name!.isEmpty {
helloLabel.text = "Hello, \(name)"
}
}
对于iOS,您可以使用其text
属性获取文本字段的字符串值:
let greeting = "Hello, \(nameField.text!.isEmpty ? "World" : nameField.text!)"
helloLabel.text = greeting
虽然text
属性是一个可选字符串,但它有一个空字符串作为默认值,所以它永远不会返回nil
,即使你为它指定了nil(感谢@Leo Dabus为注释)。
另外,您可以通过上面提到的UILabel
属性设置helloLabel
(text
)。