如何在按下按钮时从UITextField更新标签

问题描述 投票:1回答:4

所以我知道这可能是一件容易的事情,但我开始使用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”不存在。任何帮助,将不胜感激。

ios swift macos uibutton uitextfield
4个回答
0
投票
@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
}

0
投票

我想这可能对你有帮助 -

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)"
    }
}

这是输出 -

enter image description here

参考 - https://www.simplifiedios.net/xcode-text-field-tutorial-ios-using-swift/

谢谢。


0
投票

你可以做这样的事情。

@IBAction func helloButton(_ sender: Any) {
let name = txtSearch.text
        if !name!.isEmpty {
            helloLabel.text = "Hello, \(name)"
        }
}

0
投票

对于iOS,您可以使用其text属性获取文本字段的字符串值:

let greeting = "Hello, \(nameField.text!.isEmpty ? "World" : nameField.text!)"
helloLabel.text = greeting

虽然text属性是一个可选字符串,但它有一个空字符串作为默认值,所以它永远不会返回nil,即使你为它指定了nil(感谢@Leo Dabus为注释)。

另外,您可以通过上面提到的UILabel属性设置helloLabeltext)。

© www.soinside.com 2019 - 2024. All rights reserved.