gpt4 book ai didi

ios - 如何以编程方式快速从标签中的文本字段打印文本

转载 作者:行者123 更新时间:2023-11-30 12:38:09 25 4
gpt4 key购买 nike

我喜欢通过单击按钮键来打印标签中的文本字段值。但我一直无法做到。下面是代码

import UIKit

class MainViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()


view.backgroundColor = UIColor.gray
setupLabel()
setupTextField()
setupButton()
}

func setupLabel() {

let label = UILabel()
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}

func setupTextField() {

let textField = UITextField()
textField.frame = CGRect(x: 10, y: 200, width: self.view.frame.size.width - 20, height: 60)
textField.placeholder = "text here"
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 25)
textField.layer.borderWidth = 2
textField.layer.borderColor = UIColor.yellow.cgColor
textField.layer.cornerRadius = 5
view.addSubview(textField)
}

func setupButton() {

let button = UIButton()
button.frame = CGRect(x: 50, y: 300, width: self.view.frame.size.width - 100, height: 60)
button.setTitle("Enter", for: .normal)
button.setTitleColor(UIColor.yellow, for: .normal)
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.yellow.cgColor
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(buttonTarget), for: .touchUpInside)
view.addSubview(button)
}

func buttonTarget() {


// i missed of here

}
}

最佳答案

在这里您需要执行两个步骤

you need to create the label and textfield in globally not instance, for e.g

class MainViewController: UIViewController
let label = UILabel()
let textField = UITextField()

隐藏分配的实例值

  func setupLabel() {

//let label = UILabel()
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}

然后您可以直接在类中的任何位置访问该值

func buttonTarget() {

if let text = textField.text
{
label.text = text
}

}

关于ios - 如何以编程方式快速从标签中的文本字段打印文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com